Testing time in Rails with Minitest

Rails comes with time helpers that can make testing time-sensitive code effortless.

Testing time in Rails with Minitest

Time travel

Some tests are time-sensitive. Luckily for us, Rails has nice time helpers like freeze_time , travel_to , travel_back , and travel :

Time.current     # => Sat, 09 Nov 2013 15:34:49 EST -05:00
travel_to Time.zone.local(2004, 11, 24, 01, 04, 44)
Time.current     # => Wed, 24 Nov 2004 01:04:44 EST -05:00
Date.current     # => Wed, 24 Nov 2004
DateTime.current # => Wed, 24 Nov 2004 01:04:44 -0500

They also come in a block variant isolating the action we need:

# Travel forward in time
Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
travel 1.day do
  User.create.created_at # => Sun, 10 Nov 2013 15:34:49 EST -05:00
end
Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00

This way we can control time in our tests and make sure everything works as expected.

Get the book

Get the one and only book on official Rails testing strategies with Minitest and Fixtures, from the author of Kamal Handbook.

Get the book