我在Rails 3.0应用程序中指定了一个作用域,如下所示:
class DrawingList < ActiveRecord::Base
scope :active_drawings, where('start_date <= ? AND end_date >= ?', Date.today, Date.today)
end在我的规范中,我想做的是:
before do
@list = DrawingList.create #things that include begin and end dates
end
it "doesn't find an active drawing if they are out of range" do
pending "really need to figure out how to work timecop in the presence of scopes"
Timecop.travel(2.days)
puts Date.today.to_s
DrawingList.active_drawings.first.should be_nil
end正如你可能想象的那样,看跌期权实际上显示了两天后的Date.today。但是,作用域是在不同的上下文中计算的,因此它使用旧的“今天”。如何在Timecop可能影响的上下文中获得今天的评估。
谢谢!
发布于 2012-01-14 02:03:14
这是一个非常常见的错误。正如您在其中所写的,作用域使用的日期是代码加载时的日期。如果你要在生产环境中运行这个程序,只有在重启应用程序的情况下才会重新加载代码(不像开发中每次请求时都会重新加载代码),你会在重启应用程序的当天得到正确的结果,但第二天结果会提前一天,后天两天等等。
定义这样一个作用域的正确方法是
scope :active_drawings, lambda { where('start_date <= ? AND end_date >= ?', Date.today, Date.today)}lambda确保每次使用作用域时都会计算这些日期。
https://stackoverflow.com/questions/8855017
复制相似问题