TimeWithZone & Time.zone.now integration test fails

The reason is because Time.now or Time.zone.now include milliseconds (when you do a simple put to print the time it doesn't show milliseconds). However, when you persist the timestamp in the database these milliseconds likely get lost unless the db field is configured to store milliseconds. So when you read the value from the db it will not include milliseconds, hence the times are slightly different.

One solution is to remove milliseconds from Time.now. You can do this like so Time.now.change(usec: 0). This should fix the error in the tests.


The issue is that the 2 dates are very close to each other but not the same. You can use assert_in_delta

assert_in_delta @user.activation_sent_at, Time.zone.now, 1.second

For RSpec, a similar approach would be to use be_within:

expect(@user.activation_sent_at).to be_within(1.second).of Time.zone.now


The problem is that your times are very close but not quite equal. They are probably off by a few fractions of a second.

One solution to issues like this is a testing gem called timecop. It gives you the ability to mock Time.now so that it will temporarily return a specific value that you can use for comparisons.