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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)