0

我有以下 rspec 单元测试:

require 'spec_helper'

describe Article do
  describe ".recents" do
    it "includes articles created less than one week ago" do
      article = Article.create(created_at: Date.today - 1.week + 1.second)
      expect(Article.recents).to eql([article])
    end

    it "excludes articles published at midnight one week ago" do
      article = Article.create!(:created_at => Date.today - 1.week)
      expect(Article.recents).to be_empty
    end

  end
end

Article模型:

class Article < ActiveRecord::Base
  attr_accessible :description, :name, :price, :created_at

  scope :recents, where('created_at <= ?', 1.week.ago)
end

当我运行测试时,我得到:

1) Article.recents includes articles created less than one week ago
     Failure/Error: expect(Article.recents).to eql([article])

       expected: [#<Article id: 60, name: nil, description: nil, price: nil, created_at: "2012-11-14 00:00:01", updated_at: "2012-11-21 10:12:33", section_id: nil>]
            got: [#<Article id: 60, name: nil, description: nil, price: nil, created_at: "2012-11-14 00:00:01", updated_at: "2012-11-21 10:12:33", section_id: nil>]

       (compared using eql?)

       Diff:#<ActiveRecord::Relation:0x007ff692bce158>.==([#<Article id: 60, name: nil, description: nil, price: nil, created_at: "2012-11-14 00:00:01", updated_at: "2012-11-21 10:12:33", section_id: nil>]) returned false even though the diff between #<ActiveRecord::Relation:0x007ff692bce158> and [#<Article id: 60, name: nil, description: nil, price: nil, created_at: "2012-11-14 00:00:01", updated_at: "2012-11-21 10:12:33", section_id: nil>] is empty. Check the implementation of #<ActiveRecord::Relation:0x007ff692bce158>.==.
     # ./spec/models/article_spec.rb:7:in `block (3 levels) in <top (required)>'

有人可以帮我弄清楚我的测试中有什么错误吗?

这对我来说似乎很好。

4

1 回答 1

2

您正在将 activerecord 关系 ( Article.recents) 与数组 ( [article]) 进行比较,这就是预期失败的原因。(看起来它们在规范结果中是相同的,因为inspect在打印出来之前将关系转换为数组。)

将您的第一个期望更改为:

expect(Article.recents.to_a).to eql([article])
于 2012-11-21T12:00:17.640 回答