I am trying to use a combination of Timecop and querying the arel where_sql to data, but I can't seem to get Timecop to actually freeze the time. I've tried Timecop.freeze and Timecop.freeze(Time.now), both of which are slightly off when using Time.now in my spec.
What am I missing? Ruby 1.9.2, Rails 3.1.0.rc5
--
error
Failure/Error: Game.unreleased.arel.where_sql.should eq("WHERE (release_date > '#{Time.now}')")
expected "WHERE (release_date > '0000-01-01 00:00:00 -0500')"
got "WHERE (release_date > '0000-01-01 05:00:00.000000')"
model
scope :unreleased, lambda { |limit = 4| where('release_date > ?', Time.now).
order('release_date asc').
limit(limit) }
spec
it "should retrieve games with a release date later than today" do
Timecop.freeze
Game.unreleased.arel.where_sql.should eq("WHERE (release_date > '#{Time.now}')")
end
All specs pass, but Travis reports that one specs fails. Instead of expected: 2016-08-06T14:15:00Z it outputs 2016-08-06T12:15:00Z . The simple solution is to be one the same page; freezing time with some timezone (I chose 'Warsaw / Poland').
Note: Timecop. freeze will actually freeze time. This can cause unanticipated problems if benchmark or other timing calls are executed, which implicitly expect Time to actually move forward.
My usage of timecop in specs always looks like this:
Timecop.travel(Time.zone.local(2010, 6, 1, 13, 0, 0)) do
.. time sensitive spec here ..
end
It's also generally good practice to use the Time.zone proxy (Time.zone.now, Time.zone.utc, Time.zone.local, etc) when dealing with time in a rails app.
I just had a problem running Timecop with RSpec's expect
syntax when I was running:
it "updates :completed_at" do
Timecop.freeze
expect(@task.completed_at).to eq(Time.zone.now)
end
Where the times weren't matching. To solve, I put Timecop.freeze
in a before
clause.
(I realize this question is older and RSpec's expect
syntax wasn't around, but I think adding Timecop.freeze
to a before
block or clause may help people who have the same problem mentioned in the original question. Certainly, it doesn't seem like asking a new question and answering it is worthwhile since my question would be very very similar to the one above.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With