Comparing hashes in RSpec containing BigDecimal

I use RSpec (3.x) to test an object that acts like a calculator. The object places the results in a hash. But I can’t get the hash to match my tests correctly. Here is an example of what I am saying:

class ObjectUnderTest

  def calculate(a, b)
    value = a.to_d / b
    {
      value: value
    {
  end

end

The test is as follows:

RSpec.describe ObjectUnderTest do

   it "calculates the product of two values" do
     o = ObjectUnderTest.new
     expect(o.calculate(1, 3)).to eql({value: 0.333})
   end
end

The problem is that 0.333 is a float, and the actual value included in the hash is BigDecimal. If I change the line in the test to say something like:

expect(o.calculate(1, 3)).to eql({value: 0.333.to_d(3)})

... the test still fails A) because the accuracy is different, and B) in my actual code, I have several key-value pairs, and I don't want you to call k.to_d (some_precision) on everything comparison hashes to make it pass.

, - a_value_with some range, ?

+4
2

( , (0.1 + 0.2) == 0.3 false), , , . RSpec be_within(x).of(y) ( a_value_within(x).of(y)) . RSpec 3 , match matcher /, , :

expect(o.calculate(1, 3)).to match(value: a_value_within(0.001).of(0.333))
+3

You can try using eqinsteadeql

checkout rspec various equality mappings

0
source

All Articles