ruby-on-rails - 将ActiveRecord对象与Rspec进行比较

标签 ruby-on-rails activerecord rspec

在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 }


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

然后稍微复杂一些,但是有没有办法在场景上做类似的事情?说XML解析器还创建了几个属于原始对象的对象。因此,我最终得到的集合除了id,created_at和&c外应该是相同的,而且我想知道是否有一种很好的方法来测试这一点,而不仅仅是循环遍历,清除那些变量并进行检查。

最佳答案

编写上述内容的一种较短方法是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)


祝好运。

关于ruby-on-rails - 将ActiveRecord对象与Rspec进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4763983/

相关文章:

ruby-on-rails - ActiveRecord Count 用于计算 Rails 中 group by 返回的行数

sql - HABTM多 "and"查询

ruby - bundle gem : rspec says 'No examples found'

ruby-on-rails - 在 Rspec 中测试创建变量赋值

ruby-on-rails - collection_select concat firstname 和 lastname 具有相同的 id

ruby-on-rails - 在 Rails 3 中为自定义 404 捕获未知操作

ruby-on-rails - 如何覆盖 gem 中 activerecord 中的验证调用?

ruby-on-rails - 使用 RSpec 和 rails 测试 "HTML fixtures"

ruby-on-rails - 得墨忒尔法则

javascript - Rails View 中的 Javascript 问题