比较 ActiveRecord 对象与 Rspec [英] Comparing ActiveRecord objects with Rspec
问题描述
在 Rspec 中是否有一种比较两个 ActiveRecord 对象同时忽略 id 和 c 的好方法?例如,假设我从 XML 解析一个对象并从一个装置加载另一个对象,并且我正在测试的是我的 XML 解析器是否正常工作.我目前拥有的是带有
Is there a good way in Rspec to compare two ActiveRecord objects while ignoring id, &c? For example, say I'm parsing one object from XML and loading the other from a fixture, and what I'm testing is that my XML parser works correctly. What I currently have is a custom matcher with
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 }
但我想知道是否有更好的方法.
But I'm wondering if there's a better way.
然后稍微复杂一点,但是有没有办法在 set 上做类似的事情?说 XML 解析器还创建了几个属于原始对象的对象.所以我最终得到的集合应该是相同的,除了 id、created_at 和 &c,我想知道除了循环、清除这些变量和检查之外,是否有一种很好的方法来测试它.>
And then slightly more complicated, but is there a way to do a similar thing on a set? Say said XML parser also creates several objects that belong_to the original object. So the set I'm ending up with should be identical except for id, created_at, &c, and I'm wondering if there's a good way to test that beyond just cycling through, clearing out those variables, and checking.
推荐答案
编写上述内容的更短方法是 actual.attributes.except(:id, :updated_at, :created_at)
.
A shorter way to write the above would be actual.attributes.except(:id, :updated_at, :created_at)
.
如果你经常使用它,你总是可以像这样定义你自己的匹配器:
If you are using this a lot, you can always define your own matcher like this:
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
你现在可以在任何例子中说:
Put this into your spec_helper.rb
you can now say in any example:
User.first.should have_same_attributes_as(User.last)
祝你好运.
这篇关于比较 ActiveRecord 对象与 Rspec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!