Change time like Time Cop while testing in Ruby on Rails

While testing your rails application, there are many scenarios to test which are time sensitive. For example, what is the response of the app if the user has a payment delay of 2 days, or you want to have a specific time in your app to handle a specific issue. Such scenarios can be tested by TimeCop gem like charm.

Features:

Time Cop provides a lot of features which greatly help in testing:

  • Freeze time to a specific point.
  • Travel back to a specific time, but allow time to continue moving forward from there.
  • Scale time by a given scaling factor that will cause time to move at an accelerated pace.
  • No dependencies!, can be used with any ruby project
  • Timecop api allows arguments to be passed into #freeze and #travel as one of the following:
    – Time instance– DateTime instance– Date instance– individual arguments (year, month, day, hour, minute, second)– a single integer argument that is interpreted as an offset in seconds from Time.now
  • Nested calls to Timecop#travel and Timecop#freeze are supported -- each block will maintain its interpretation of now.
  • Works with regular Ruby projects, and Ruby on Rails projects

Usage examples:

Run a time-sensitive test

Freeze time, so that system clock doesn’t start

Travel to a future time


Happy Coding!