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

时间:2013-06-24 16:07:54

标签: ruby-on-rails ruby rspec 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>

这是我正在尝试运行的测试:

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

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

感谢您的任何见解...

1 个答案:

答案 0 :(得分:3)

Notifier,根据其名称,是一个常数。

您无法使用allowdouble加倍常量。相反,您需要使用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)

编辑:修复了stub()调用

的语法错误
相关问题