Sunday, August 2, 2009

Turn off auto-dating for ActiveRecord in tests

Fixtures have one nice characteristic. setting updated_at and created_at in them overrides what ActiveRecord would normally record. When using Factories (like factory_girl), want to have a way to turn the auto-dating off and on.

Michał Szajbe at Code Tunes provides this useful tidbit.

Add a small bit of code to test_helper.rb inside TestCase
  def without_timestamping_of(*klasses)
if block_given?
klasses.delete_if { |klass| !klass.record_timestamps }
klasses.each { |klass| klass.record_timestamps = false }
begin
yield
ensure
klasses.each { |klass| klass.record_timestamps = true }
end
end
end
After that, just wrap Factory calls in without_timestamping_of to turn off dating.
  without_timestamping_of Article, Comment, User do
Factory(:article, :created_at => 1.week.ago, :updated_at => 1.week.ago)
Factory(:comment, :created_at => 1.day.ago)
Factory(:user, :updated_at => 5.hours.ago)
end
Simple and very useful. Many thanks again to Michał Szajbe at Code Tunes

No comments:

Post a Comment