Rails 测试具有日期范围的 named_scope [英] Rails Testing a named_scope with a date range
问题描述
场景
我在名为last_week"的模型上有一个 named_scope.它所做的只是获取上周的记录.
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.
我不能使用 RSpec、Shoulda 或其他 3rd 方客户端插件.我只被允许使用摩卡咖啡.
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.
推荐答案
首先你的范围是错误的:因为代码是即时执行的,你的日期范围条件将取决于你启动服务器的时间...
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...
替换为:
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
创建两条记录
设置 created_at
1 周 + 1 天前为一条记录
set created_at
1 week + 1 day ago for one record
检查你的范围只检索一个(正确的)
check your scope only retrieves one (the proper one)
这篇关于Rails 测试具有日期范围的 named_scope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!