我们应该为连接表模型创建制造商吗?

时间:2016-10-10 09:28:43

标签: ruby-on-rails rspec has-many-through jointable

我在2个模型之间创建了一个连接表来表示它们之间的“多对多”关系(带有has_many: through关联)。

我现在正在编写测试,我想知道是否应该为该连接表模型创建一个Fabricator?我的连接表只有2个相关模型的外键。

1 个答案:

答案 0 :(得分:1)

您只需要在测试中创建模型的工厂。

例如,如果你有:

class User
  has_many :user_projects
  has_many :projects, through: :user_projects
end

class UserProject
  belongs_to :user
  belongs_to :project
end

class Project
  has_many :user_projects
  has_many :users, through: :user_projects
end

您并不需要UserProject的工厂,因为ActiveRecord会在需要时创建连接模型。

Fabricator(:user) do
  projects(count: 3)
end

Fabricator(:project) do
  user
end

然而,如果" pivot" model不仅仅是一个简单的连接表,并且有自己的属性,为该对象创建一个工厂通常很有用:

class User
  has_many :lists
  has_many :tasks, through: :lists
end

class List
  belongs_to :user
  has_many :tasks
end

class Task
  belongs_to :list
  has_one :user, through: :list
end

Fabricator(:list) do
  name { 'Shopping List' }
  user
  tasks(count: 3)
end