Rails Testing a named_scope with a date range

元气小坏坏 提交于 2020-01-14 06:29:53

问题


SCENARIO
I have a named_scope on a model called 'last_week'. All it does is it fetches the records from last week.

I want to test this and my approach is to test that the results coming back are within a certain range. I don't know if this is the right way of testing this functionality on a class method.

I can't use RSpec, Shoulda or other 3rd party client plugin. I am only allowed to use Mocha if I want.

# Model

class Article < ActiveRecord::Base

  scope :last_week,   :conditions => { :created_at => 1.week.ago..DateTime.now.end_of_day }

end


#Test

class ArticleTest < ActiveSupport::TestCase

  test "named scope :last_week " do
    last_week_range = DateTime.now.end_of_day.to_i - 1.week.ago.to_i
    assert_in_delta last_week_range, Article.last_week.first.created_at - Article.last_week.last.created_at,  last_week_range
  end

end

Looking for feedback on what's right or wrong about this approach.


回答1:


First your scope is wrong: because code is executed on the fly your date range condition will depend on the time you booted your server...

Replace with:

scope :last_week,  lambda { :conditions => { :created_at => 1.week.ago..DateTime.now.end_of_day } }

Second, to test, I'd create some records and check if the scope get the proper ones:

  • create a factory

  • create two records

  • set created_at 1 week + 1 day ago for one record

  • check your scope only retrieves one (the proper one)



来源:https://stackoverflow.com/questions/12204010/rails-testing-a-named-scope-with-a-date-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!