RSpec matcher to check if two numbers are the same

Updated . Posted . Visible to the public.

You can usually just use the eq matched to compare two numbers:

expect(deal.total).to eq(120)

If the actual value is a BigDecimal, you might have issues when you match it against a Float:

expect(deal.total_price).to eq(1200.99)

In these cases, try matching it against another BigDecimal:

expect(deal.total_price).to eq BigDecimal(1200.99)

If you don't like the syntax, our rspec_candy Show archive.org snapshot gem has a matcher that will compare Fixnums (integers), Floats and BigDecimals with each other:

expect(deal.total_price).to be_same_number_as(1200.99)

This compares the numbers' #to_s representation.

Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2010-12-13 22:33)