【问题标题】:Rspec new expectation syntaxRspec 新的期望语法
【发布时间】:2012-11-21 10:15:53
【问题描述】:

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

还有Articlemodel:

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

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

这对我来说似乎很好。

【问题讨论】:

    标签: rspec2 rspec-rails


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢。它似乎有效,但不应该在文档上发表评论。在进行比较之前是否需要转换为Array
    • 这不是真正的 rspec 问题,因此无需记录。在控制台中尝试相同的操作,即:Article.recents.eql?([article]),你会看到结果是 false,因为 Article.recents 是一个 ActiveRecord::Relation 而[article] 是一个数组。
    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多