2009-12-28 54 views
28

在rspec(1.2.9)中,指定對象每次都會接收對具有不同參數的方法的多次調用的正確方法是什麼?RSpec:每次指定對具有不同參數的方法的多次調用

我問,因爲這個混亂的結果:

describe Object do 

    it "passes, as expected" do 
    foo = mock('foo') 
    foo.should_receive(:bar).once.ordered.with(1) 
    foo.should_receive(:bar).once.ordered.with(2) 
    foo.bar(1) 
    foo.bar(2) 
    end 

    it "fails, as expected" do 
    foo = mock('foo') 
    foo.should_receive(:bar).once.ordered.with(1) # => Mock "foo" expected :bar with (1) once, but received it twice 
    foo.should_receive(:bar).once.ordered.with(2) 
    foo.bar(1) 
    foo.bar(1) 
    foo.bar(2) 
    end 

    it "fails, as expected" do 
    foo = mock('foo') 
    foo.should_receive(:bar).once.ordered.with(1) 
    foo.should_receive(:bar).once.ordered.with(2) 
    foo.bar(2) # => Mock "foo" received :bar out of order 
    foo.bar(1) 
    end 

    it "fails, as expected, but with an unexpected message" do 
    foo = mock('foo') 
    foo.should_receive(:bar).once.ordered.with(1) 
    foo.should_receive(:bar).once.ordered.with(2) 
    foo.bar(1) 
    foo.bar(999) # => Mock "foo" received :bar with unexpected arguments 
       # => expected: (1) 
       # =>   got (999) 
    end 

end 

我預計將 「預期:(2)」 最後的失敗消息,而不是 「預期(1)」。我用錯了rspec嗎?

回答

28

類似於question。推薦的解決方案是撥打as_null_object以避免混淆消息。所以:

describe Object do 
    it "fails, as expected, (using null object)" do 
    foo = mock('foo').as_null_object 
    foo.should_receive(:bar).once.ordered.with(1) 
    foo.should_receive(:bar).once.ordered.with(2) 
    foo.bar(1) 
    foo.bar(999) # => Mock "foo" expected :bar with (2) once, but received it 0 times 
    end 
end 

輸出是不一樣的你的第二個案件(即「有望2,但得到999」),但它確實表明,期望沒有實現。

+0

這樣更好:它將錯誤信息從錯誤的「Expected(1)got(999)」更改爲「expected:bar with(2)」一次,但收到它0次。「不完全符合要求,但至少它不像我所得到的那樣是一個平坦的謊言。但現在它未能檢測到:foo.bar(1); foo.bar(999); foo.bar(2)。看起來好像人們爲了獲得更真實的錯誤信息而必須交換檢測一些錯誤的能力。我知道,不是你的錯。 – 2009-12-29 13:59:41

相關問題