The Ruby core language and standard library include two classes that represent timestamps: Time and DateTime. And even though they fill similar needs, they have different internals and aren’t comparable.
1 2 3 4 5 6 7 8 9 10 11
Rails adds the ActiveSupport::TimeWithZone class and extends the core classes in a number of ways including by allowing comparison of instances of different classes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
In most cases, this frees you up to write code without having to explicitly convert between types or even know which types you’re comparing. But eventually you might find yourself try to test the equality of two timestamps which should logically be the same:
The error message in this case only deepens the mystery:
1 2 3
The thing to remember here is that all of these classes store timestamps with much more precision than they usually display. In the case of ActiveSupport::TimeWithZone, that goes down to millisecond and even nanosecond precision.
1 2 3 4 5 6 7 8 9 10
So when we want to compare timestamps that we know to be unequal, the usual operators (
<, …) are fine. But if we’re checking for relative equality, we’ll need to use some representations of the timestamps.
In The Minitest Cookbook I advised developers to compare dates and times using a string representation since, when you do fail a test, the message returned will usually be meaningful.
I still think that’s the way to go when you’re comparing generated data with a constant value, but in other cases like where you’re checking the equality of two generated values, it’s usually better to compare numeric representations of the timestamps as:
1 2 3
Keep in mind that there’s always the chance that the two timestamps might be generated across a second boundary which would cause the test as written to fail. If you’re looking for some additional insurance for this situation, you could also assert that the numeric representations of the timestamps are within a delta of one another:
1 2 3 4