How do I create an association with a has_many :through relationship in Factory Girl?

☆樱花仙子☆ 提交于 2019-12-03 21:11:33

For such a factory you need to use callbacks of factory girl. Try this:

FactoryGirl.define do
  factory :user do
    ...
  end

  factory :admin, :parent => :user do 
    after_create {|u| Factory(:assignment, :role => Factory(:role, :name => 'admin', :value => 'admin'), :user => u)}
  end

  factory :role do
    ...
  end

  factory :assignment do
    user {|a| a.association(:user)}
    role {|a| a.association(:role)}
  end
end

@kshil is correct but you can tighten up the code a little and make it more modular.

Create a second :role factory for the admin user.

factory :role do
  name 'Normal'
  value 'normal'

  factory :admin_role do
    name  'admin'
    value  'admin'
  end
end

Also, if a factory name is the same as the association name you can leave out the factory name. The :assignment factory becomes:

factory :assignment do
  user
  role
end

Define the :admin_user factory inside the :user factory and you don't have to specify the parent factory. You would also probably to add two factories to define both normal and admin users.

factory :user do
  sequence(:username) { |n| "user#{n}" }
  email { "#{username}@example.com" }
  password 'secret'
  password_confirmation 'secret'

  factory :normal_user do
    after_create {|u| Factory(:assignment, :user => u)}
  end

  factory :admin_user do
    after_create {|u| Factory(:assignment, :role => Factory(:admin_role), :user => u)}
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!