I have a rails structure of a user that's something like this:
User.create(
email: 'asdf@test.com',
password: 'testtest',
password_confirmation: 'testtest'
).memberships.create(
role_id: 1
)
Where,
Role.create(
name: 'admin'
)
How can I create this association in FactoryGirl?
Models:
User.rb
has_many :memberships
has_many :roles, through: :memberships
Membership.rb
belongs_to :user
belongs_to :role, dependent: :destroy
Role.rb
has_many :memberships, dependent: :destroy
has_many :users, through: :memberships
It depends on the associations you use. Here is an example for a has many association
factory :user do
email "asdf@test.com"
password "testtest"
password_confirmation "testtest"
role
end
which creates the user and with the call of 'role' the association will be set
factory :role do
name "admin"
end
regarding your comment, try this:
factory :user do
email "asdf@test.com"
password "testtest"
password_confirmation "testtest"
role
end
factory :role do
name "admin"
end
factory :membership do
user
role
end
This is how you would use child factories to model this while maintaining admin and non-admin factories
factory :user do
sequence(:email) { |n| "user#{n}@rmail.com" }
password "supersecret"
password_confirmation { |u| u.password }
factory :admin do
admin_membership
end
end
factory :membership do
user
role
factory :admin_membership do
admin_role
end
end
factory :role do
name "role"
factory :admin_role do
name "admin"
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.