Rspec any_instance.stub 引发 nil:NilClass 异常的未定义方法 `any_instance_recorder_for'

2024-03-31

这是我正在测试的类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 https://www.relishapp.com/rspec/rspec-mocks/v/2-6/docs/method-stubs/stub-on-any-instance-of-a-class给出的例子是在我的机器上传递的(所以这不是 rspec 代码的问题),但它没有给我任何关于我可能做错的事情的信息。错误消息也很令人困惑,因为它告诉我不要打电话.any_instance on a nil:NilClass,但正如我用我的输出证明的那样,Foo isn't nil。我该怎么打电话.any_instance.stub在我的自定义对象上?

我正在使用红宝石1.9.3和 rspec2.14.5.


你应该使用before(:each)用于存根。

存根于before(:all)不支持。原因是在每个示例之后所有存根和模拟都会被清除,因此设置的任何存根before(:all)将在恰好在该组中运行的第一个示例中起作用,但不适用于任何其他示例。

rspec-mocks 自述文件 https://github.com/rspec/rspec-mocks#use-beforeeach-not-beforeall

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rspec any_instance.stub 引发 nil:NilClass 异常的未定义方法 `any_instance_recorder_for' 的相关文章

随机推荐