Time comparison in Ruby

I believe every ruby developer has faced time comparison issue at least once and tests are one of the possible areas where it may happen. RSpec message like this may confuse:What’s wrong?


Let’s create two Time objects:At the first glance, they are equal. But it’s not true:The issue occurs because ruby Time makes comparison with fractions of seconds. We may use to_f method to see the difference between t1 and t2:or to_r method to get rational numbers:


If you don’t care about milliseconds, you may compare timestamps using to_i method:or make a new Time object from timestamps to have better RSpec failure messages:But even better to use fixed times in our tests.