![ruby timecop ruby timecop](https://www.goncalopereira.com/blog/2016-09-06_development-quality-for-ruby-and-chef/images/2.png)
In addition to the freeze_time there are also other useful methods grouped into the ActiveSupport::Testing::TimeHelpers module. According to its release note it a dds freeze_time helper which freezes time to Time.now in tests. Otherwise Timecop::SafeModeException is raised ?.Īnd that had been, more or less, an approach we took until Ruby on Rails 5.2 was released. Today I learned that there is a Timecop.safe_mode method which forces using the block syntax.
![ruby timecop ruby timecop](https://dmcca.be/assets/work/full/lc-3-db0d6e2b42e458cf54da95ebe2288a8d.png)
To make the failing tests, we can freeze time: describe Building doįinished in 0.62 seconds (files took 2.63 seconds to load)Ī common issue I have observed over time is calling eeze without a block and forgetting about Timecop.return to put time back the way it was.
![ruby timecop ruby timecop](https://64.media.tumblr.com/c9428a89ee7ade93e11567be17e78f26/bbedaeb09a74cd7c-ec/s1280x1920/aa38c7080e2603b2f14ecdd130b3bc98bdfdb701.jpg)
You know what they say – time flies when you’re having fun ?. It 'returns time displayed by the clock' doĮxpect(described_).to eq Īnd, surprisingly or not, the test didn’t pass: expected: 19:26:14.958265000 +0000 To cover the #clock method with rspec we could use the below lines: describe Building do
#Ruby timecop code
To better illustrate when the gem may be useful, let’s write down some naive lines of code representing a building with a clock ⏰: class Building It provides a unified method to mock Time.now, Date.today, and DateTime.now in a single call. Among Rubyists, the most popular gem which provides handy helpers to this problem is called timecop:Ī gem providing “time travel”, “time freezing”, and “time acceleration” capabilities, making it simple to test time-dependent code. Sooner or later each of us encounters a situation where a method depends on time. Please remember about unfreezing time in tests, regardless of an approach you choose. TLDR Since Ruby on Rails 5.2 timecop gem can be replaced by built-in methods defined within the ActiveSupport::Testing::TimeHelpers module.