2012-07-03 37 views
1

考慮以下兩個平凡型號:should_receive做我不指望的事嗎?

class Iq 

    def score 
    #Some Irrelevant Code 
    end 

end 

class Person 

    def iq_score 
    Iq.new(self).score #error here 
    end 

end 

而下面的Rspec的測試:

describe "#iq_score" do 

    let(:person) { Person.new } 

    it "creates an instance of Iq with the person" do 
    Iq.should_receive(:new).with(person) 
    Iq.any_instance.stub(:score).and_return(100.0) 
    person.iq_score 
    end 

end 

當我運行這個測試(或者說,類似的一個),它出現在短線有沒有工作:

Failure/Error: person.iq_score 
    NoMethodError: 
    undefined method `iq_score' for nil:NilClass 

失敗,你可能會猜到,在上面標有「error here」的行上。當should_receive行被註釋掉時,此錯誤消失。這是怎麼回事?

+0

您是否嘗試刪除'with'方法或添加'and_return'方法? –

+0

刪除'with'調用不起作用。假設'Iq'實例尚未創建,我將使用什麼作爲'和return'的參數? – hoffm

+0

mock_model(Iq).as_null_object –

回答

3

你磕碰掉初始化:

Iq.should_receive(:new).with(person) 

返回nil,所以Iq.new爲零。要解決,只是這樣做:

Iq.should_receive(:new).with(person).and_return(mock('iq', :iq_score => 34)) 
person.iq_score.should == 34 // assert it is really the mock you get 
7

由於RSpec的已擴展stubber功能,現在下面的方法是正確的:

Iq.should_receive(:new).with(person).and_call_original 

將(1)檢查預期(2)控制返回到原來的功能,不只是返回零。

+0

非常感謝!它幫了我很多:) –

+0

正是我在找的東西! – benastan

相關問題