Nick Nick - 7 months ago 45
Ruby Question

TimeWithZone & Time.zone.now integration test fails

In a controller method I set a user's variable

activation_sent_at
equal to
Time.zone.now
when an activation email is sent to that user. On the development server this seems to work (although time expressions in my application are 2 hours behind on the local time of my computer).

I want to include an integration test that tests whether
activation_sent_at
indeed gets set properly. So I included the line:

assert_equal @user.activation_sent_at, Time.zone.now


However, this produces the error:

No visible difference in the ActiveSupport::TimeWithZone#inspect output.
You should look at the implementation of #== on ActiveSupport::TimeWithZone or its members.


I think it's suggesting to use another expression for
Time.zone.now
in my test. I've looked at different sources, including http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html, but am not sure what to do here. Any suggestions what could be causing this error?

Additional info: Adding
puts Time.zone.now
and
puts @stakeholder.activation_sent_at
confirms the two are equal. Not sure what generates the failure/error.

AbM AbM
Answer

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

Comments