【问题标题】:Rspec any_instance.stub raises undefined method `any_instance_recorder_for' for nil:NilClass exceptionRspec any_instance.stub 为 nil:NilClass 异常引发未定义的方法“any_instance_recorder_for”
【发布时间】:2013-09-11 11:33:46
【问题描述】:

这是我正在测试的包含在 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

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

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

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

    rspec-mocks readme

    【讨论】:

      【解决方案2】:

      从 Rspec 3 开始,any_instance 不再定义。

      现在使用:

      allow_any_instance_of(Foo).to receive(:bar).and_return(1)
      

      此版本和旧版本的来源: https://makandracards.com/makandra/2561-stub-methods-on-any-instance-of-a-class-in-rspec-1-and-rspec-2

      【讨论】:

        【解决方案3】:

        更新rspec 对我有用。您可以使用以下命令来完成:

        bundle update rspec

        【讨论】:

        • 我的 rspec 是最新版本,换句话说,当我运行 sudo gem update 时,没有任何升级。你用的是什么版本的rpsec
        • 我目前正在使用rspec 2.14.1,它工作正常。我遇到了和rspec 2.14.0 一样的问题。
        • 我正在使用2.14.5,但有趣的是它在2.14.0 对你有用
        • 它确实在2.14.1 工作,没有尝试更高。您是否尝试过降级以查看是否可以解决问题?
        • 我实际上意识到我的问题不是在 before(:all) 中存根,这似乎是您的问题,而是一个常规存根问题。
        猜你喜欢
        • 1970-01-01
        • 2017-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-31
        相关资源
        最近更新 更多