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 money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
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)