2013-11-24 39 views
1

這裏是我的測試:RSPEC - 預期VS收到的錯誤

describe Item do 
    subject {Item.new(:report_id => 26 , :name => 'Gas' , :tax_rate => 0.13, :tax_id => 1 , :category_id => 15 , :sub_category_id => 31 , :job_id => 1 , :total => 20)} 

    let(:tax) {Tax.where(id: subject.tax_id).first} 
    let(:sub_category) {SubCategory.where(id: subject.sub_category_id).first} 


    it 'Calculate with just Total' do 

    subject.name.should be == 'Gas' 
    tax = Tax.find_by_id(subject.tax_id) 
    subject.sub_category_id.should be == 31 
    subject.set_nil_values 
    sub_category.should_receive(:taxable).and_return(1) 
    tax.should_receive(:rate).and_return(0.13) 
    sub_category.should_receive(:tax_adjustment).and_return(nil) 
    subject.should_receive(:tax_rate).and_return(0.13) 
    subject.calculate_tax(tax, sub_category) 
    subject.tax_amount = (((subject.total - subject.deduction) - ((subject.total - subject.deduction)/(1 + 0.13))) * 1) 
    subject.calculate_cost 
    subject.cost.should be_within(0.01).of(17.70) 

    end 

這是我的錯誤:

1) Item Calculate with just Total 
    Failure/Error: subject.should_receive(:tax_rate).and_return(0.13) 
     (#<Item:0x007faab7299c30>).tax_rate(any args) 
      expected: 1 time with any arguments 
      received: 3 times with any arguments 
    # ./spec/models/item_spec.rb:25:in `block (2 levels) in <top (required)>' 

我做了一些研究,並試圖使用它代替:

expect_any_instance_of(subject).to receive(:tax_rate) 

但現在出現以下錯誤:

1) Item Calculate with just Total 
    Failure/Error: expect_any_instance_of(subject).to receive(:tax_rate) 
    NoMethodError: 
     undefined method `method_defined?' for #<Item:0x007fe6fdaa1bf8> 
    # ./spec/models/item_spec.rb:25:in `block (2 levels) in <top (required)>' 

回答

1

您的初始錯誤發生是因爲,如錯誤消息所述,所討論的方法被稱爲三次而不是一次,這是隱含的期望。假設實際的行爲是應該的,你可以改變的期望是:

...receive(...).exactly(3).times 

更多信息,請參見http://rubydoc.info/gems/rspec-mocks/frames

至於你遇到的第二個錯誤,根據我的測試,這發生在你使用expect_any_instance_of的類已經有一個實例存在,然後你調用該存根實例。在任何情況下,即使這種方法奏效,我也不相信這是你想要的,因爲expect_any_instance_of的頻率語義與expect相同,即「一個(全部)呼叫通過存根實例(s )」。

如果第二個錯誤發生,但您沒有刪除subject上的現有期望,請告訴我。

+0

嘿 - 我該如何傳遞它應該返回的結果? – fatfrog

+1

只需像以前那樣添加'.and_return(...)'。 –

+0

太棒了!謝謝! – fatfrog

相關問題