gpt4 book ai didi

ruby - Rspec any_instance.stub 为 nil :NilClass exception 引发未定义的方法 `any_instance_recorder_for'

转载 作者:数据小太阳 更新时间:2023-10-29 06:47:32 25 4
gpt4 key购买 nike

这是我正在测试的包含在 Foo.rb 中的类:

class Foo
def bar
return 2
end
end

这是 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

我正在使用 Ruby 1.9.3 和 rspec 2.14.5

最佳答案

您应该使用 before(:each) 进行 stub 。

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 in before(:all) would work in the first example that happens to run in that group, but not for any others.

rspec-mocks readme

关于ruby - Rspec any_instance.stub 为 nil :NilClass exception 引发未定义的方法 `any_instance_recorder_for',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18740030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com