2017-11-21 5 views
0

の範囲内であり、基本的に私がしようとしているRSpecのテストレコードは、私は私のモデルの内側にこのスコープ機能を備えています日付

SELECT `posts`.* FROM `posts` 
WHERE (`posts`.`created_at` BETWEEN '2017-10-01 00:00:00' AND '2017-10-31 23:59:59') 

特定の年と月のアーカイブされたすべての記事を返す

# 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) 

要求された年と月に投稿が作成されたことを確認するためにこのメソッドのテストを書くにはどうしたらいいですか?

# 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 

答えて

1

結果セットに含まれているレコードを確認するためにinclude matcherを使用してください。

expect(Post.filtered({year: Date.today.strftime("%Y"), month: Date.today.strftime("%m")}).to include(newer) 
+0

この 'expect()。(より新しい).to_not include(古い)'を期待する方がいますか?基本的には2つ書きするのではなく1つの期待で – Lykos

1

を使用すると、注文を無視する必要がある場合に要素を一致させることができます。

# 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 

エンド

ところで、代わりにあなたがここに何をしたかのようなクラスメソッドを作成する、あなたはそれが他のスコープを連鎖させることができますので、スコープを検討する必要があります。

関連する問題