[英]Using Timecop gem For Scopes
我在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可以影響的上下文中進行評估。
謝謝!
這是一個非常常見的錯誤。 正如您在范圍使用的日期所寫的那樣,是加載代碼時的日期。 如果你重新啟動應用程序(不像每次請求重新加載的開發),你是否只在重新加載代碼的生產中運行它,你會在重新啟動應用程序的那天獲得正確的結果,但第二天結果將在一天之內,第二天之后出現等等。
定義這樣的范圍的正確方法是
scope :active_drawings, lambda { where('start_date <= ? AND end_date >= ?', Date.today, Date.today)}
lambda確保每次使用范圍時評估這些日期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.