All Lessons / Testing Times & Dates with Rails

Testing Times & Dates with Rails

#320 ยท November 20, 2019

Your Teacher

Hi, I'm Chris. I'm the creator of GoRails, and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

About This Episode

Rails provides several helper methods for testing times and dates in your applications. You can now freeze time and time travel like in the movies!


Testing times and dates can be particularly tricky. Time always keeps ticking forward and dealing with timezones and other things can be a huge pain.

Rails provides some tools for helping test times and dates. Timecop is a popular gem you might have heard of or used in the past, but Rails actually comes with some built-in helpers.

The easiest place to start is to use the "freeze_time" method. It simply stubs out the,, and methods with the current time. It will continue to return the exact same time until you call "unfreeze_time".

The "travel" and "travel_to" helpers can freeze time to a specific time in the past or future. They can also accept a block to have time frozen only within the block.

After your tests, the stubs will be cleared out automatically so you don't have to worry about time changes affecting other tests.

If you're testing things like trials, calendar events, or other date and time calculations, these tools are invaluable for making sure your code works as expected.



logo Created with Sketch.

Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

© 2023 GoRails, LLC. All rights reserved.