ruby-on-rails - 如何在我的规范中使用 Timecop 正确地卡住时间?

标签 ruby-on-rails ruby-on-rails-3 testing rspec

我正在尝试结合使用 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

最佳答案

我在规范中对 timecop 的使用总是如下所示:

Timecop.travel(Time.zone.local(2010, 6, 1, 13, 0, 0)) do
  .. time sensitive spec here ..
end

在 Rails 应用程序中处理时间时,使用 Time.zone 代理(Time.zone.now、Time.zone.utc、Time.zone.local 等)通常也是一种好的做法。

关于ruby-on-rails - 如何在我的规范中使用 Timecop 正确地卡住时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6838688/

相关文章:

ruby-on-rails - 如何在页面加载时加载嵌入的 ruby​​ javascript 文件?

ruby-on-rails-3 - 无法在 Mountain Lion 上安装 rmagick gem

ruby-on-rails-3 - Mac 上的开发模式是瘦还是 unicorn ?

javascript - 使用 greasemonkey 脚本自动化 flash 应用程序

reactjs - 如何测试异步/等待 API 调用和更新 React 状态

ruby-on-rails - 从嵌套类中调用 Ruby 模块方法

ruby-on-rails - 如何修复 PG::DuplicatePstatement: ERROR?

ruby-on-rails - ruby rails : How to model a "user favorite model"

ruby-on-rails-3 - Mongoid动态查询

c# - Visual Studio 负载测试结果存储库空间不足