如何正确检查结果集是否为 ActiveRecord::Associations::CollectionProxy

ope*_*per 0 ruby activerecord rspec ruby-on-rails

我想检查我的结果集是否属于类型ActiveRecord::Associations::CollectionProxy

例如我的模型如下

class Dashboard < ApplicationRecord
  has_and_belongs_to_many :organisations
end
Run Code Online (Sandbox Code Playgroud)
class Organisation < ApplicationRecord
  has_and_belongs_to_many :dashboards
end
Run Code Online (Sandbox Code Playgroud)

当我这样做时,organisation.dashboards我想检查一下是否是ActiveRecord::Associations::CollectionProxy

但像下面这样的东西不起作用。

expect(organisation.dashboards).to be(ActiveRecord::Associations::CollectionProxy)
Run Code Online (Sandbox Code Playgroud)

任何帮助都会非常好,谢谢。

Sam*_*dhe 5

您可以在此处使用 rspec类型匹配器

Expect(obj).to be_kind_of(type):调用 obj.kind_of?(type),如果 type 位于 obj 的类层次结构中或者是一个模块并且包含在 obj 的类层次结构中的类中,则返回 true。

expect(organisation.dashboards).to be_kind_of(ActiveRecord::Associations::CollectionProxy)
Run Code Online (Sandbox Code Playgroud)

或者

expect(organisation.dashboards).to be_a_kind_of(ActiveRecord::Associations::CollectionProxy)
Run Code Online (Sandbox Code Playgroud)

或者

expect(organisation.dashboards).to be_a(ActiveRecord::Associations::CollectionProxy)
Run Code Online (Sandbox Code Playgroud)