Read more

RSpec matcher to check if two numbers are the same

Henning Koch
December 13, 2010Software engineer at makandra GmbH

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

expect(deal.total).to eq(120)
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Henning Koch to makandra dev (2010-12-13 23:33)