Reputation: 879
I have two models, User and Answer. I would like to generate a user_id in the FactoryGirl creation of Answer. How would I go about this?
FactoryGirl.define do
factory :user do
name { Faker::Name.name }
pasword { 'password' }
password_confirmation { |u| u.password }
end
end
And the following is what I have so far for generating a foreign user_id (obviously incorrect syntax):
FactoryGirl.define do
factory :answer do
description { Faker::Lorem.words }
user_id = FactoryGirl.create(:user)::user_id
end
end
Upvotes: 0
Views: 81
Reputation: 2135
You could do something like the following:
FactoryGirl.define do
factory :answer do
description { Faker::Lorem.words }
after(:build) do |answer, evaluator|
answer.user = create(:user) unless answer.user
end
end
end
This will create a new user if a user isn't provided when creating the answer.
Upvotes: 0
Reputation: 38645
Given the association answer belongs_to: :user
, you can use association
helper in factory definition as:
FactoryGirl.define do
factory :answer do
description { Faker::Lorem.words }
association :user
end
end
Then the usage:
u = FactoryGirl.create(:user)
answer = FactoryGirl.create(:answer, user: u)
Upvotes: 2