我喜欢RSpec,我非常喜欢它的=~
数组运算符匹配器来验证数组是否包含一组特定的元素,无论是否排序。
但毫不奇怪,它测试指针相等,而不是内容相等,所以以下内容不起作用:
class Flea < ActiveRecord::Base ; end
class Dog < ActiveRecord::Base
has_many :fleas
end
@d = Dog.create
@d.fleas << (@f1 = Flea.create)
@d.fleas << (@f2 = Flea.create)
@d.fleas.should =~ [@f1, @f2]
所以我发现自己经常在我的RSpec测试中写这个:
@d.fleas.map {|f| f.id}.should =~ [@f1.id, @f2.id]
...... bad code smell充满了热情。 RSpec是否提供了更好的方法来验证ActiveRecord对象的集合,无论返回的顺序如何?或者至少有一种更漂亮的方法来编写这样的测试?
答案 0 :(得分:4)
ActiveRecord :: Relations不像Arrays(你发现的那样)。请参阅Issue #398 on the GitHub RSpec-Rails Issue board。
答案是将这行代码添加到spec_helper.rb
:
RSpec::Matchers::OperatorMatcher.register(ActiveRecord::Relation, '=~', RSpec::Matchers::MatchArray)