Rspec新的期望语法

时间:2012-11-21 10:15:54

标签: rspec2 rspec-rails

我有以下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)>'

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

对我来说似乎很好。

1 个答案:

答案 0 :(得分:2)

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

将您的第一个期望改为:

expect(Article.recents.to_a).to eql([article])