我们应该为 join table 模型创建制造器吗?
Should we create fabricators for a join table model?
我在两个模型之间创建了一个连接 table 来表示它们之间的 'many-to-many' 关系(具有 has_many: through
关联)。
我现在正在编写测试,我想知道是否应该为该连接 table 模型创建一个 Fabricator?我的连接table只有2个相关模型的外键。
您真正需要的只是您将在测试中创建的模型的工厂。
例如,如果您有:
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" 模型不仅仅是一个简单的连接 table 并且具有自己的属性,那么为该对象创建一个工厂通常很有用:
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
我在两个模型之间创建了一个连接 table 来表示它们之间的 'many-to-many' 关系(具有 has_many: through
关联)。
我现在正在编写测试,我想知道是否应该为该连接 table 模型创建一个 Fabricator?我的连接table只有2个相关模型的外键。
您真正需要的只是您将在测试中创建的模型的工厂。
例如,如果您有:
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" 模型不仅仅是一个简单的连接 table 并且具有自己的属性,那么为该对象创建一个工厂通常很有用:
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