我在我的模型中有这个范围功能
# models/Post.rb
def self.filtered (params)
unless params[:year].blank? && params[:month].blank?
year = params[:year].to_i
month = params[:month].to_i
return where(created_at: DateTime.new(year, month, 1).beginning_of_day..DateTime.new(year, month, -1).end_of_day)
end
self
end
# controllers/posts_controller.rb
@posts = Post.filtered(params)
基本上返回特定年份和月份的所有存档帖子
SELECT `posts`.* FROM `posts`
WHERE (`posts`.`created_at` BETWEEN '2017-10-01 00:00:00' AND '2017-10-31 23:59:59')
我正在尝试为此方法编写测试,以确保在请求的年份和月份中创建了帖子,我该怎么做?
# spec/models/post_spec.rb
describe '.filtered' do
let!(:older) { FactoryGirl.create(:post, created_at: 1.month.ago) } # this post should not appear in the list
let!(:newer) { FactoryGirl.create(:post, created_at: Time.zone.now) } # this post should appear in the list
it 'is within specific year and month' do
expect(Post.filtered({year: Date.today.strftime("%Y"), month: Date.today.strftime("%m")}).map { |post| post.created_at }).to be ???
end
end
答案 0 :(得分:1)
使用include matcher验证结果集中是否包含记录。
expect(Post.filtered({year: Date.today.strftime("%Y"), month: Date.today.strftime("%m")}).to include(newer)
答案 1 :(得分:1)
在忽略订单时,使用#contain_exactly
匹配元素。
# spec/models/post_spec.rb
describe '.filtered' do
let!(:older) { FactoryGirl.create(:post, created_at: 1.month.ago) } # this post should not appear in the list
let!(:newer) { FactoryGirl.create(:post, created_at: Time.zone.now) } # this post should appear in the list
it 'is within specific year and month' do
expect(Post.filtered({year: Date.today.strftime("%Y"), month: Date.today.strftime("%m")}).map { |post| article.created_at }).to contain_exactly(newer)
end
端
顺便说一下,您可能想要考虑范围,以便与其他范围链接,而不是像您在此处创建类方法一样。