如何在我的规范中使用 Timecop 正确冻结时间?
我正在尝试结合使用 Timecop 和查询 arel where_sql 数据,但我似乎无法让 Timecop 真正冻结时间。我尝试过 Timecop.freeze 和 Timecop.freeze(Time.now),在我的规范中使用 Time.now 时,这两个方法都略有偏差。
我缺少什么? Ruby 1.9.2、Rails 3.1.0.rc5
--
错误
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')"
模型
scope :unreleased, lambda { |limit = 4| where('release_date > ?', Time.now).
order('release_date asc').
limit(limit) }
规范
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我在规范中对 timecop 的使用总是如下所示:
在处理时间时,使用 Time.zone 代理(Time.zone.now、Time.zone.utc、Time.zone.local 等)通常也是一种很好的做法。导轨应用程序。
My usage of timecop in specs always looks like this:
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.
我刚刚在运行时使用 RSpec 的
expect
语法运行 Timecop 时遇到了问题:时间不匹配。为了解决这个问题,我将
Timecop.freeze
放在before
子句中。(我意识到这个问题比较旧,并且 RSpec 的
expect
语法不存在,但我认为将Timecop.freeze
添加到before
块或子句可能会帮助那些在原始问题中提到相同问题的人。当然,提出一个新问题并回答它似乎并不值得,因为我的问题与上面的问题非常相似。)I just had a problem running Timecop with RSpec's
expect
syntax when I was running:Where the times weren't matching. To solve, I put
Timecop.freeze
in abefore
clause.(I realize this question is older and RSpec's
expect
syntax wasn't around, but I think addingTimecop.freeze
to abefore
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.)前往日期并包括 TimeHelpers,例如:
Travel to the date and include TimeHelpers, example: