Read more

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

Henning Koch
March 09, 2011Software engineer at makandra GmbH

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 ==)
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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 Time.now 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(Time.now.round) 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.

Posted by Henning Koch to makandra dev (2011-03-09 19:49)