travisjeffery / timecop

A gem providing "time travel", "time freezing", and "time acceleration" capabilities, making it simple to test time-dependent code. It provides a unified method to mock Time.now, Date.today, and DateTime.now in a single call.
MIT License
3.37k stars 226 forks source link

named_scope seems to not work? #4

Closed futurechimp closed 15 years ago

futurechimp commented 15 years ago

I am not totally sure whether I'm just doing something wrong or whether this is a bug, but I'm trying to find Order objects which need to be delivered on Date.today, with a named_scope like this:

  named_scope :for_today,
              :include => [:delivery => :delivery_slot],
              :conditions => ['delivery_slots.date = ?', Date.today],
              :order => 'delivery_slots.timeslot'

and in a console session:

  >> Order.for_today.count  
  => 9
  >> require 'timecop'
  => []
  >> Timecop.travel(Date.today + 1) do 
  ?> Order.for_today.count 
  >> end
  => 9
  >> Timecop.travel(Date.today + 5) do 
  ?> Order.for_today.count
  >> end
  => 9
  >> Timecop.travel(Date.today + 5) do 
  ?> puts Date.today
  >> end
  2009-11-11 # <= this is correct as right now it's 6 Nov.
  => nil
  >> Timecop.travel(Date.today + 500) do 
  ?> Order.for_today.count
  >> end
  => 9
  >> quit

There are definitely no orders which have an associated Delivery which is 500 days in the future, so I'm wondering whether this is perhaps a bug with named_scope?

jtrupiano commented 15 years ago

@futurechimp, this is a problem that many folks run into. The issue is how your named_scope is being defined. What happens is Date.today is being interpreted when the file is loaded, not when the named_scope is invoked. If you change the named_scope declaration to use a lambda as below, this will all work as expected.

named_scope :for_today, lambda {
  { :include => [:delivery => :delivery_slot],
    :conditions => ['delivery_slots.date = ?', Date.today],
    :order => 'delivery_slots.timeslot' }
}

This is a common mistake many people make when defining named_scopes that depend on time and is not a problem specific to Timecop.

-John