是否有Rspec的一个很好的方式来比较两个ActiveRecord对象而忽略了ID,和C?例如,假设我解析XML从一个对象并加载另一个从夹具,什么我测试的是,我的XML解析器正常工作。我现在有一个自定义的匹配与
actual.attributes.reject {|键,V | %W标识的updated_at created_at.INCLUDE?关键} == expected.attributes.reject {|键,V | %W标识的updated_at created_at.INCLUDE?键 }
但我不知道是否有一个更好的办法。
然后稍微复杂一些,但有没有办法做类似的事情上的设置的?萨伊说,XML解析器还创建belong_to原始对象多个对象。因此,集,我结束了应该是除了身份证,created_at,与放大器相同的; C,我想知道是否有用于测试超过了通过只是骑自行车,清理掉这些变量,并检查的好办法 解决方案
一个简写形式,上面会 actual.attributes.except(:ID,:的updated_at,:created_at)
。
如果您在本使用了很多,你总是可以这样定义自己的匹配:
的RSpec :: Matchers.define:have_same_attributes_as做|期望|
比赛做|实际|
忽略= [:ID,:的updated_at,:created_at]
actual.attributes.except(*忽略)== expected.attributes.except(*忽略)
结束
结束
将这个到你的 spec_helper.rb
,你现在可以说在任何例如:
User.first.should have_same_attributes_as(User.last)
祝你好运。
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.
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.
解决方案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
Put this into your spec_helper.rb
you can now say in any example:
User.first.should have_same_attributes_as(User.last)
Good luck.