Testing time dependent features - Hives/acebook-business-logic GitHub Wiki

We were asked to implement a feature where posts are only editable for 10 minutes after they've been created. How do you test something that depends on time though? You can't tell your test to wait for 10 minutes.

Answer - we used a gem called Timecop which allows you to freeze time, and to 'time travel' to points in the past or future. Our test looked like this:

scenario "The edit link doesn't appear if a post is 10 minutes old" do
  sign_up
  create_post
  Timecop.freeze(601)
  visit "/posts"
  expect(page).not_to have_link("Edit")
end

Timecop.freeze(601) freezes time at a point 601 seconds in the future, i.e. 10 minutes and 1 second.

There are various other ways you can pass in arguments, e.g. as a time or datetime instance or by specifying year, month and day.

One other cool thing we found out - Rails has got date helpers like 10.minutes.ago and 2.days.since which came in very handy for this feature.