Rails Testing a named_scope with a date range

2019-06-08 19:06发布

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条回答
我欲成王,谁敢阻挡
2楼-- · 2019-06-08 19:45

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)

查看更多
登录 后发表回答