ruby-on-railsrubyrspectimecop

Timecop does not work with DateTime attributes defined in FactoryGirl


I have the following factory:

FactoryGirl.define do
  factory :task do
    due_date 7.days.from_now
  end
end

In my specs, I'm using Timecop in this way:

before do
  Timecop.freeze(Time.parse("Oct 5 2015"))
end

Time.now and Date.today are being stubbed with the given time as expected, but the due_date attribute of the factory always returns based on the date of the system, and I would like it to return based on the date provided in Timecop. Is it possible?

I'm using Ruby 2.2.2, Rails 3.2.22, Timecop 0.8.0 and Rspec 3.1.0.


Solution

  • Pass the value to a block, so that it's evaluated on call, not when the factories definition is loaded. This is called Lazy attributes, more about that here

    FactoryGirl.define do
      factory :task do
        due_date { 7.days.from_now }
      end
    end