【发布时间】:2012-07-04 08:13:04
【问题描述】:
考虑以下两个简单的模型:
class Iq
def score
#Some Irrelevant Code
end
end
class Person
def iq_score
Iq.new(self).score #error here
end
end
以及以下 Rspec 测试:
describe "#iq_score" do
let(:person) { Person.new }
it "creates an instance of Iq with the person" do
Iq.should_receive(:new).with(person)
Iq.any_instance.stub(:score).and_return(100.0)
person.iq_score
end
end
当我运行这个测试(或者,更确切地说,一个类似的测试)时,存根似乎没有工作:
Failure/Error: person.iq_score
NoMethodError:
undefined method `iq_score' for nil:NilClass
正如您可能猜到的那样,失败出现在上面标有“此处错误”的行上。当should_receive 行被注释掉时,这个错误就消失了。怎么回事?
【问题讨论】:
-
您尝试删除
with方法还是添加and_return方法? -
删除
with调用无效。鉴于尚未创建Iq实例,我将使用什么作为and return的参数? -
mock_model(Iq).as_null_object
-
Iq.should_receive(:initialize).with(person)呢?
标签: ruby testing rspec stubbing expectations