Posted about 10 years ago. Visible to the public. Repeats.

Why two Ruby Time objects are not equal, although they appear to be

So you are comparing two Time objects in an RSpec example, and they are not equal, although they look equal:

expected: Tue May 01 21:59:59 UTC 2007, got: Tue May 01 21:59:59 UTC 2007 (using ==)

The reason for this is that Time actually tracks fractions of a second, although #to_s doesn't say so and even though you probably only care about seconds. This means that two consecutive calls of probably return two inequal values.

Consider freezing time in your tests so it is not dependent on the speed of the executing PC:

Timecop.freeze( do time1 = ... time2 = ... expect(time1).to eq(time2) end

Note for users of #end_of_day

Rails extends Time with a method #end_of_day which returns the latest possible Time on the same day. The exact value for this is 23:59:59.999999 in Ruby 1.8 and 23:59:59.999999999 in Ruby 1.9.

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Henning Koch
Last edit:
almost 2 years ago
by Besprechungs-PC
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more