rspec-mocks 'allow' 返回未定义的方法

Jes*_*ord 5 ruby rspec ruby-on-rails rspec-mocks

我正在使用 RSpec2 v2.13.1,它似乎应该包含rspec-mocks ( https://github.com/rspec/rspec-mocks )。当然它列在我的 Gemfile.lock 中。

但是,当我运行测试时,我得到

     Failure/Error: allow(Notifier).to receive(:new_comment) { @decoy }
 NoMethodError:
   undefined method `allow' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x007fc302aeca78>
Run Code Online (Sandbox Code Playgroud)

这是我尝试运行的测试:

require 'spec_helper'

describe CommentEvent do

  before(:each) do
    @event = FactoryGirl.build(:comment_event)
    @decoy = double('Resque::Mailer::MessageDecoy', :deliver => true)
    # allow(Notifier).to receive(:new_comment) { @decoy }
    # allow(Notifier).to receive(:welcome_email) { @decoy }
  end

  it "should have a comment for its object" do
    @event.object.should be_a(Comment)
  end

  describe "email notifications" do
    it "should be sent for a user who chooses to be notified" do
      allow(Notifier).to receive(:new_comment) { @decoy }
      allow(Notifier).to receive(:welcome_email) { @decoy }
      [...]
    end
Run Code Online (Sandbox Code Playgroud)

目标是消除通知程序和消息诱饵,以便我可以测试我的 CommentEvent 类是否确实在调用前者。我在 rspec-mocks 文档中读到 before(:all) 不支持存根,但它在 before(:each) 中也不起作用。帮助!

感谢您的任何见解...

Bil*_*han 4

Notifier顾名思义,是一个常量。

您不能使用 或allow来将常量加倍double。相反,您需要使用stub_const

# Make a mock of Notifier at first
stub_const Notifier, Class.new

# Then stub the methods of Notifier
stub(:Notifier, :new_comment => @decoy)
Run Code Online (Sandbox Code Playgroud)

编辑:修复了 Stub() 调用的语法错误

  • 这并没有解决我的问题......而且你有一个大括号结尾而不是一个括号。我的错误是 NoMethodError: undefined method `allow' for #&lt;SpecHelperClass:0x007fc3c2372f20&gt;,.. 听起来像 rspec 模块需要在运行时包含在该类中... (3认同)