Posted 8 months ago. Visible to the public. Repeats. Linked content.

ActiveSupport includes Timecop-like helpers

ActiveSupport (since 4.1) includes test helpers to manipulate time, just like the Timecop gem:

  • To travel a relative amount of time, use travel:

    Copy
    travel 1.day
  • To travel to a specific moment in time, use travel_to:

    Copy
    travel_to 1.hour.from_now
  • To freeze a specific time, use freeze_time (ActiveSupport 5.2+):

    Copy
    freeze_time 1.hour.from_now

All those methods may also receive a block to call and restore time afterwards. If you don't provide a block, you must call travel_back or unfreeze_time once you are done.

Simply load the TimeHelpers module as required by your test framework. Example:

Copy
RSpec.configure do |config| config.include ActiveSupport::Testing::TimeHelpers end

Note that we love Timecop and that it may be better suited for some use cases (for example, it includes Timecop.scale and a Timecop.safe_mode configuration setting), but for most projects you actually may not need Timecop.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Arne Hartherz
Last edit:
about 1 month ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more