简体   繁体   中英

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

In my models I have the following setup:

class User < ActiveRecord::Base
  has_many :assignments
  has_many :roles, :through => :assignments
end


class Role < ActiveRecord::Base
  has_many :assignments
  has_many :users,  :through => :assignments
end

class Assignment < ActiveRecord::Base
  belongs_to :user
  belongs_to :role

  attr_accessible :role_id, :user_id
end

In my factory.rb file I have:

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

    factory :admin  do
      ...
    end
  end

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

  factory :assignment do
    ...
  end
end

I'm struggling to figure out how I would add a role with, :name => "admin", :value => "admin", to the "admin" factory inside the "user" block so I can call

create(:admin)

in my tests and have a user with the admin role.

Thank you for looking.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM