There are some bugs that only appear under certain circumstances. Today was the day I’ve got one of those (there is a hint in this sentence).
I pushed a small change and got a red build as a result. I already had the corresponding test fixed so red build was not something I was expecting.
An exception I’ve got was from a check in
TicketTransferPolicy which had nothing at all to do with my changes. And so the investigation began.
raise DeadlinePassed if deadline_passed?(event)
def deadline_passed?(event) if FT.on?(:extended_tickets_transfer_deadline, organizer_id: event.user_id) event.ends_at < Time.current else event.starts_at < Time.current.advance(days: 1) end end
Hint: failing test was not related to extended deadline.
I’ve looked into the failing test and here’s the line that instantly got my attention:
event = test_organizer.create_published_event(starts_at: 25.hours.from_now)
This was an instant ‘aha’ moment when I’ve realized, today’s the day when we have 25 hours in the day.
In my opinion, the best solution here is to use
Time.current.advance(days: 1, hours: 1) in the test instead of
25.hours.from_now, this approach is more consistent with the code we’re testing.
26 would also work ;)
Thanks, DST :P
Would you like to continue learning more?
If you enjoyed that story, subscribe to our newsletter. We share our every day struggles and solutions for building maintainable Rails apps which don’t surprise you.
You might enjoy reading:
- inject vs each_with_object
- The === (case equality) operator in Ruby explained
- Relative Testing vs Absolute Testing - the mentioned test is only using relative time in a setup. It could be nice to have 3 absolute tests checking a normal day, DST started day and DST ended day.
- Falsehoods programmers believe about time - it starts with There are always 24 hours in a day :)
Also, make sure to check out our latest book Domain-Driven Rails. Especially if you work with big, complex Rails apps.