2013-06-24 122 views
4

我正在使用RSpec2 v2.13.1,它似乎應包含rspec-mocks(https://github.com/rspec/rspec-mocks)。當然,它在我的Gemfile.lock中列出。rspec-mocks'allow'返回未定義的方法

然而,當我跑我的測試中,我得到

 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)中不支持存根,但它在之前(:每個)中都不起作用。幫幫我!

感謝您的任何見解...

回答

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) 

編輯:存根上的固定語法錯誤()調用

+0

在你說憑什麼說'allow'和'double'是一樣的嗎?根據文檔或來源,它們看起來不一樣。 –

+0

@ PeterAlfvin,檢查此:https://github.com/rspec/rspec-mocks#method-stubs「rspec-mocks支持3種形式來聲明方法存根」 –

+0

@PeterAlfvin,根據示例代碼,效果是相同的。無論如何,我刪除了最後一行,這與答案無關。當'double'和'stub'足夠好的時候,我很少使用'allow',這看起來沒有必要。 –

相關問題