'体重转换器'
试图摆脱使用存根但我无法正确使用格式,我有什么不对?我知道在这种情况下我已经在代码中使用了该方法,但我正在尝试学习如何正确地执行存根。
测试
describe "Convert Pounds to Kilograms" do
it "should convert 3lb to 1kg" do
weight = WeightConverter.stub!(:convert).with(3, 'lbs_to_kgs').and_return(1)
weight.should == 1
end
代码:
class WeightConverter
def self.convert(from, what_to_what)
if what_to_what == 'lbs_to_kgs'
(from / 2.2).truncate
elsif what_to_what == 'kgs_to_lbs'
(from * 2.2).truncate
end
end
end
fyi - 这可行(没有存根)
it "should convert 91lbs to 41kgs" do
weight = WeightConverter.convert(91, 'lbs_to_kgs')
weight.should == 41
end
错误:
故障:
1) Convert Pounds to Kilograms should convert 3lb to 1kg
Failure/Error: weight.should == 1
expected: 1
got: #<Proc:0x000000010b0468@/home/durrantm/.rvm/gems/ruby-1.9.3-p125/gems/rspec-mocks-2.10.1/lib/rspec/mocks/message_expectation.rb:459 (lambda)> (using ==)
# ./weight_converter_spec.rb:19:in `block (2 levels) in <top (required)>'
Finished in 0.00513 seconds
7 examples, 1 failure
答案 0 :(得分:2)
你不想分配到存根,而应该做这样的事情:
it "should convert 3lb to 1kg" do
WeightConverter.stub!(:convert).with(3, 'lbs_to_kgs').and_return(1)
weight = WeightConverter.convert(3, 'lbs_to_kgs')
weight.should == 1
end
然而,这是一个相当无用的测试 - 它唯一测试的是你的存根/模拟库做它应该做的事情(即它实际上根本没有测试WeightConverter)。由于您正在直接测试WeightConverter的内部,因此您无需将其存根。您应该使用第二个示例中的实际值。但是,如果WeightConverter依赖于另一个类,则可能存根该另一个类。