RSPEC测试记录在日期范围内



我在模型中具有此范围函数

# 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

使用Include Matcher验证结果集中的记录。

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

在应忽略订单时使用 #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

结束

顺便说一句,您可能需要考虑一个范围,而不是创建类似的类方法,因此可以使用其他范围链接。

最新更新