Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 625
danielricecodes Avatar asked Mar 14 '19 18:03

danielricecodes


1 Answers

When testing floating point numbers, I recommend you use RSpec's be_within matcher.

Example:

expect(my_float).to be_within(0.01).of(0.69)

You should choose a resolution that makes sense for your use case. (0.001, 0.0001, etc.)

like image 53
Fito von Zastrow Avatar answered Oct 04 '22 22:10

Fito von Zastrow