Rspec any_instance.stub 为 nil:NilClass 异常引发未定义的方法 `any_instance_recorder_for' [英] Rspec any_instance.stub raises undefined method `any_instance_recorder_for' for nil:NilClass exception
问题描述
这是我正在测试的包含在 Foo.rb 中的类:
Here is the class that I'm testing contained in Foo.rb:
class Foo
def bar
return 2
end
end
这是我在 Foo_spec.rb 中包含的测试:
Here is the my test contained in Foo_spec.rb:
require "./Foo.rb"
describe "Foo" do
before(:all) do
puts "#{Foo == nil}"
Foo.any_instance.stub(:bar).and_return(1)
end
it "should pass this" do
f = Foo.new
f.bar.should eq 1
end
end
我得到以下输出:
false
F
Failures:
1) Foo Should pass this
Failure/Error: Foo.any_instance.stub(:bar).and_return(1)
NoMethodError:
undefined method `any_instance_recorder_for' for nil:NilClass
# ./Foo_spec.rb:6:in `block (2 levels) in <top (required)>'
Finished in 0 seconds
1 example, 1 failure
Failed examples:
rspec ./Foo_spec.rb:9 # Foo Should pass this
我咨询过the doc 和给出的示例在我的机器上传递(所以它不是 rspec 代码的问题),但它没有给我任何关于什么的信息我可能做错了.错误消息也很令人困惑,因为它告诉我不要在 nil:NilClass
上调用 .any_instance
,但正如我用我的输出证明的那样,Foo
不是 nil
.我应该如何在我的自定义对象上调用 .any_instance.stub
?
I've consulted the doc and the example given is passing on my machine (so it isn't a problem with the rspec code), but it isn't giving me any information on what I might be doing wrong. The error message is also quite confusing as it's telling me not to call .any_instance
on a nil:NilClass
, but as I proved with my output, Foo
isn't nil
. How am I supposed to call .any_instance.stub
on my custom object?
我使用的是 Ruby 1.9.3
和 rspec 2.14.5
.
I'm using Ruby 1.9.3
and rspec 2.14.5
.
推荐答案
你应该使用 before(:each)
进行 stubbing.
You should use before(:each)
for stubbing.
不支持 before(:all)
中的存根.原因是所有的存根和模拟在每个示例之后都被清除,所以在 before(:all)
中设置的任何存根都可以在碰巧在该组中运行的第一个示例中工作,但不能对于任何其他人.
Stubs in
before(:all)
are not supported. The reason is that all stubs and mocks get cleared out after each example, so any stub that is set inbefore(:all)
would work in the first example that happens to run in that group, but not for any others.
这篇关于Rspec any_instance.stub 为 nil:NilClass 异常引发未定义的方法 `any_instance_recorder_for'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!