Search code examples
rubyrspecmatcher

Random RSpec failures comparing Floats (Eq matcher)


I'm not even sure where to begin here. Sorry if this is a duplicate, but I don't even know what to search for or what this particular issue is called.

Randomly, and not all that often, a test in my RSpec suite will fail and I'll get an error like this:

expected: 0.69
     got: 0.69 (0.69e0)

(compared using ==)

The RSpec code is comparing two Floats, from two different models, that should be the same value when the spec is done. Is there a way to reproduce this in a command console? I've tried the obvious stuff (below) but I am honestly at a loss. If I rerun the test a dozen times, I can't reproduce the issue.

0.69 == 0.69e0 => true
0.69 == 0.69 => true
6.9e-1 == 0.69 => true

Solution

  • This is a general problem testing floating point numbers. I always convert them to strings for comparison when using RSpec:

    expect(float.to_s).to eq '0.69'