0

I am trying to wrap Timecop around a shared_example spec i wrote

describe "timecop wrapping shared example" do
   Timecop.freeze(1.day.ago) do
      it_behaves_like "a shared example i would like to test using timecop"
   end
end

shared_examples "a shared example i would like to test using timecop"
   before :all do
      puts "the current time is #{Time.now}"
   end

   ... expect ...
end

but running this spec still uses the real time and not the frozen one

can Timecop work like this?

how else can i wrap large pieces of my test file but change the time it is running

amitben
  • 670
  • 10
  • 21

1 Answers1

2

Timecop needs to execute within an it or before block.

The following change will fix your problem.

describe "timecop wrapping shared example" do before { Timecop.freeze(1.day.ago) } it_behaves_like "a shared example i would like to test using timecop" end

Rspec will reset the environment(including Timecop) after running each example.

A couple of tips I've found with time travel in tests that might be useful:

  • Timecop.travel is more reflective of how your code will work in real life as time never stays still. You can use it the same way as freeze, just swap out the freeze method for travel.

  • If you have Rails 4.1 or newer there are great time travel tools built in and you can drop your timecop gem. Here is a blog post and the docs if you want to learn more.

Teresa
  • 75
  • 7
  • i wanted it to be run in a block because if my shared_example uses as well Timecop.freeze (and it does), when it Timecop.return, it will return to my original "real" time and not the frozen time that wrapped the shared example. – amitben Aug 19 '17 at 09:02
  • Is rspec not cleaning up your environment in between examples? If it's not there could be something wrong with your rspec setup. Another option is to use [around instead of before](https://relishapp.com/rspec/rspec-core/v/2-0/docs/hooks/around-hooks) – Teresa Aug 20 '17 at 16:26
  • shared_example call will "reset" the time back to the current time. if i would have written the shared example in the describe "timecop wrapping shared example", it would all worked fine – amitben Aug 21 '17 at 11:09