Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io 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 Time.now, DateTime.now, and Date.today 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.