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

祝好运。