Using Timecop Gem for Areas

I review the scope of Rails 3.0 as follows:

class DrawingList < ActiveRecord::Base scope :active_drawings, where('start_date <= ? AND end_date >= ?', Date.today, Date.today) end 

In my specification, I want:

 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 

As you can imagine, puts really shows that Date.today is two days. However, the area is evaluated in a different context, so it uses the old "today." How to get an assessment today in a context that may affect Timecop.

Thanks!

+6
source share
1 answer

This is a really common mistake. As you wrote in the date used by the area, this is the date it was downloaded. If you started it in production, when the code rebooted only when the application was restarted (unlike development, where it reboots for each request), you will get the correct results on the day you restarted the application, but the next day the results will be one day, the next day for 2 days, etc.

The correct way to define such an area is

 scope :active_drawings, lambda { where('start_date <= ? AND end_date >= ?', Date.today, Date.today)} 

The lambda ensures that these dates will be evaluated every time the area is used.

+18
source

Source: https://habr.com/ru/post/905934/


All Articles