11
有這結果,我想檢查的方法:四捨五入問題RSpec的測試,比較浮陣列時
result.should == [1.0,2.0,3.0]
但我得到一個錯誤:
expected: [1.0, 2.0, 3.0]
got: [1.0, 2.0, 3.0] (using ==)
我認爲問題在於舍入,但我不知道如何比較它們,例如0.1的偏差。
謝謝,apneadiving。 我寫自己的匹配,如果幫助別人:
RSpec::Matchers.define :be_closed_array do |expected, truth|
match do |actual|
same = 0
for i in 0..actual.length-1
same +=1 if actual[i].round(truth) == expected[i].round(truth)
end
same == actual.length
end
failure_message_for_should do |actual|
"expected that #{actual} would be close to #{expected}"
end
failure_message_for_should_not do |actual|
"expected that #{actual} would not be close to #{expected}"
end
description do
"be a close to #{expected}"
end
end
謝謝你,我知道這些方法,但我不知道如何將它們應用於數組。我已經迭代每個值?因爲這行結果應該是_ close([1.0,2.0,3.0],0.1),不起作用。 – zolter
嗯......不知道。你最好創建自己的匹配器,它非常直接 – apneadiving
由於RSpec 3只有'be_within'被實現:http://www.rubydoc.info/gems/rspec-expectations/3.1.0/RSpec/Matchers#be_within-instance_method vs http://www.rubydoc.info/gems/rspec-expectations/2.4.0/RSpec/Matchers#be_close-instance_method – Raf