2011-07-28 46 views
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 

回答

13

用途:

.should be_close 

甚至:

.should be_within 

参考这里http://rubydoc.info/gems/rspec-expectations/2.4.0/RSpec/Matchers

+0

谢谢你,我知道这些方法,但我不知道如何将它们应用于数组。我已经迭代每个值?因为这行结果应该是_ close([1.0,2.0,3.0],0.1),不起作用。 – zolter

+1

嗯......不知道。你最好创建自己的匹配器,它非常直接 – apneadiving

+1

由于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