【问题标题】:Should we create fabricators for a join table model?我们应该为连接表模型创建制造商吗?
【发布时间】:2016-10-10 09:28:42
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案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”模型不仅仅是一个简单的连接表,并且有自己的属性,那么为该对象创建一个工厂通常很有用:

    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
    

    【讨论】:

    • 这很有意义,谢谢@max。但是,当您说“您实际上并不需要 UserProject 的工厂,因为 ActiveRecord 在需要时会创建连接模型。”,has_many :through 关联也是如此吗?
    • 是的,在第一个示例中,user.projects.createproject.users.create 也会在 user_projects 中插入一条记录。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 2014-08-03
    相关资源
    最近更新 更多