Ruby on rails 如何在rspec中测试ActiveRecords集合?

Ruby on rails 如何在rspec中测试ActiveRecords集合?,ruby-on-rails,activerecord,rspec,Ruby On Rails,Activerecord,Rspec,我喜欢RSpec,我非常喜欢它的=~数组操作符匹配器来验证数组是否包含一组特定的元素,而不考虑顺序 但毫不奇怪,它测试的是指针相等性,而不是内容相等性,因此以下内容不起作用: class Flea < ActiveRecord::Base ; end class Dog < ActiveRecord::Base has_many :fleas end @d = Dog.create @d.fleas << (@f1 = Flea.create) @d.fleas &

我喜欢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是否提供了一种更好的方法来验证ActiveRecord对象的集合,而不管返回的顺序如何?或者至少有更漂亮的方法来编写这样的测试吗?

ActiveRecord::Relationships不像数组那样工作(正如您所发现的)。看

答案是将这行代码添加到
spec\u helper.rb

RSpec::Matchers::OperatorMatcher.register(ActiveRecord::Relation, '=~', RSpec::Matchers::MatchArray)

我不认为这是一个答案,因为我相信它也有味道,但你可以做
@d.flea\u ids
而不是映射。没错,但你的方法更像是一种气味,而不是臭味……)哦,那太骗人了!我的意思是我希望我先想到这一点:)干得好。它是有效的。谢谢(从RSpec链接,显然你也可以做
[*@d.fleals]。应该=~[@f1,@f2]
,但是注册匹配器感觉是更好的方法。)注意,这现在是标准的-你不需要注册自己的匹配器来处理
ActiveRecord::Relations
RSpec::Matchers::OperatorMatcher.register(ActiveRecord::Relation, '=~', RSpec::Matchers::MatchArray)