Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding problem with rspec tests when comparing float arrays

There is a method which result I want to check:

 result.should  == [1.0,2.0,3.0]

But I get an error:

   expected: [1.0, 2.0, 3.0]
        got: [1.0, 2.0, 3.0] (using ==)

I think the problem in rounding, but I don `t know how compare them, for example with a deviation of 0.1.

Thank you, apneadiving. I wrote my own matcher, if it help someone:

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
like image 378
zolter Avatar asked Jul 28 '11 08:07

zolter


1 Answers

Use (deprecated since 2.7.0, removed in 3.0.0):

 .should be_close

Or even:

 .should be_within

Ref here http://rubydoc.info/gems/rspec-expectations/2.4.0/RSpec/Matchers

like image 171
apneadiving Avatar answered Sep 23 '22 03:09

apneadiving