Reputation: 3417
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.
Upvotes: 2
Views: 998
Reputation: 9604
@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
Upvotes: 3
Reputation: 6168
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
Upvotes: 5