approximately

Facilitates comparisons of Floats, primarily in mocking. Some mocking libraries will not allow you to put delta assertions within the expectations of your method calls. For example:

some_animated_point = mock()
some_animated_point.should_receive(:move_to).with(0.01456, -234.786)

Then you feed this mock from the outside, using some iterative algorithm with arbitrary precision, and your assertion fails.

Expectation not matched: called "move_to" with (0.01455999, -234.78576)

This comes because what you should have done is comparing within a delta/epsilon value instead of comparing verbatim.

However, once the expected argument has been swallowed by the mocking library you don’t really have any control on what is going to happen to it, and in most mocking libraries you cannot add detailed assertions on the expectation arguments.

So what we can do instead is create a special object that will be equal to another Float object when they both are in delta of one another. For example:

Approximately.approx(23.4, 0.1) == 23.44 # true

In your unit testing/spec framework du jour your test would look like this:

include Approximately

some_animated_point = mock()
some_animated_point.should_receive(:move_to).with(approx(0.01456, 0.001), approx(-234.786, 0.001))

These objects will compare properly with your reference inputs.

You can also get this magic float object without including Approximately by calling

Approximately.approx(23.4, 0.1)

This module is completely uninvasive and contains no hacks for minitest, RSpec or other testing/mocking frameworks.

Contributing to approximately

Copyright © 2012 Julik. See LICENSE.txt for further details.