How can I make this Time assertion match perfectly with either Time, Date, or DateTime
Using Time#to_i isn't the best solution. If the task you are running takes more than a second the comparison would fail. Even if your task is fast enough, this comparison would fail:
time = Time.now # 2018-04-18 3:00:00.990
# after 20ms
assert_equal Time.now.to_i, time.to_i # Fails
Time.now would be 2018-04-18 3:00:01.010
and to_i would give you 2018-04-18 3:00:01
and time was 2018-04-18 3:00:00.990
and to_i: 2018-04-18 3:00:00
. So the assert fails.
So, sometimes the test would pass and others would fail, depending on when (in miliseconds) it starts.
The better solution is to freeze the Time. You could use a gem like Timecop or write your own code, like (using MiniTest):
current_time = Time.now
# You need Mocha gem to use #stubs
Time.stubs(:now).returns(current_time)
You can also use a block, so that after the block the clock is back to normal
# For this you don't need Mocha
Time.stub :now, current_time do # stub goes away once the block is done
assert your_task
end
Old but still valid... The output shows that the comparison is against UTC which would be Time.current
At this time you would probably use:
assert_in_delta object.sent_at, Time.current, 1
To tolerate <1 second difference
I think it is easiest to use Time#to_i to compare the time in seconds.
assert_equals object.sent_at.to_i, Time.now.to_i # seconds