我有一个名为calculate_total的昂贵方法。我需要一个返回calculate_total结果的名为total的方法。后续对total的调用应该会返回之前的calculate_total结果。
我想以一种测试驱动的方式来做这件事。以下是我的测试(我使用RSpec):
describe Item do
describe "total" do
before do
@item = Item.new
@item.stub!(:calculate_total => 123)
end
it "returns the calculated total" do
@item.total.should == 123
end
it "subsequent calls return the original result" do
previous_total = @item.total
@item.total.should equal(previous_total)
end
end
end这不是一个好的测试,因为下面的方法使测试通过,但我预计第二个测试会失败:
def total
calculate_total
end原因是calculate_total返回一个Fixnum,所以ruby看不到结果是两个不同的对象。我预计第二次测试会失败,因此我可以执行以下操作来使其通过:
def total
@total ||= calculate_total
end有没有人知道更好的测试方法?
我不认为这是测试它的最好的/正确的方法,但我决定这样做:https://gist.github.com/1207270
发布于 2011-09-10 04:56:55
我认为您的要点很好:您想要测试的是calculate_total是否被多次调用,而这正是您正在做的事情。我可能建议的唯一区别是一个稍微更明确的测试:
it "subsequent calls don't calculate the total, but still return the original result" do
@item.should_receive(:calculate_total).once
2.times do
@item.total.should == 123
end
end发布于 2012-01-21 01:54:23
您可以在同一规范中调用它两次,并比较返回的对象以确保它们相等:
it "should memoize it" do
total = Item.total
# second call will yield a different object if not memoized
Item.total.should == total
endhttps://stackoverflow.com/questions/7367000
复制相似问题