Read more

Timecop: reset after each test

Avatar
Daniel Stra├čner
January 11, 2023Software engineer at makandra GmbH

Timecop Show archive.org snapshot is a great gem to set the current time in tests. However, it is easy to introduce flakyness to your test suite when you forget to reset the time after the test.
This might be the case if:

  • a test freezes time and a later test does not work for frozen time
  • a later test needs the real current date to work correctly
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more

Often you only notice these kinds of errors in rare cases when tests are executed in a particular order.

A way to avoid this is by using block notation (Timecop.travel(...) do) as this will automatically reset the time after the block.

My advice is to generally reset manipulated time after each test, so a developer can never forget to clean up.

reset after each spec

Reset after each spec by putting this to your spec_helper.rb:

config.after(:each) do
  Timecop.return
end

reset after each feature

Put this to something like features/support/timecop.rb or features/step_definitions/time_steps.rb

After do
  Timecop.return
end
Posted by Daniel Stra├čner to makandra dev (2023-01-11 11:21)