【问题标题】:Comparing ActiveRecord objects with Rspec将 ActiveRecord 对象与 Rspec 进行比较
【发布时间】:2011-01-21 21:30:34
【问题描述】:

在 Rspec 中是否有一个很好的方法来比较两个 ActiveRecord 对象而忽略 id、&c?例如,假设我从 XML 解析一个对象并从夹具加载另一个对象,而我正在测试的是我的 XML 解析器工作正常。我目前拥有的是带有

的自定义匹配器
actual.attributes.reject{|key,v| %w"id updated_at created_at".include? key } == expected.attributes.reject{|key,v| %w"id updated_at created_at".include? key }

但我想知道是否有更好的方法。

然后稍微复杂一些,但是有没有办法在 set 上做类似的事情?说 XML 解析器还创建了几个属于原始对象的对象。所以我最终得到的集合应该是相同的,除了 id、created_at 和 &c,我想知道除了循环、清除这些变量和检查之外,是否有一种很好的方法来测试它。

【问题讨论】:

    标签: ruby-on-rails activerecord rspec


    【解决方案1】:

    上面写的更短的方法是actual.attributes.except(:id, :updated_at, :created_at)

    如果你经常使用它,你总是可以像这样定义自己的匹配器:

    RSpec::Matchers.define :have_same_attributes_as do |expected|
      match do |actual|
        ignored = [:id, :updated_at, :created_at]
        actual.attributes.except(*ignored) == expected.attributes.except(*ignored)
      end
    end
    

    把它放到你的spec_helper.rb 你现在可以在任何例子中说:

    User.first.should have_same_attributes_as(User.last)
    

    祝你好运。

    【讨论】:

    • 对我来说它只适用于引号["id", "updated_at", "created_at"]
    • 要使其同时处理字符串和符号,您可以使用 HashWithIndifferentAccess: actual.attributes.with_indifferent_access.except...
    • 我在尝试这个时得到undefined method attributes'`。有什么问题?
    猜你喜欢
    • 1970-01-01
    • 2012-01-21
    • 2022-09-30
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 2018-04-06
    • 2018-06-22
    相关资源
    最近更新 更多