FactoryGirl override attribute of associated object
According to one of FactoryGirl's creators, you can't pass dynamic arguments to the association helper (Pass parameter in setting attribute on association in FactoryGirl).
However, you should be able to do something like this:
FactoryGirl.define do factory :profile do transient do user_args nil end user { build(:user, user_args) } after(:create) do |profile| profile.user.save! end endend
Then you can call it almost like you wanted:
p = FactoryGirl.create(:profile, user_args: {email: "test@test.com"})
I think you can make this work with callbacks and transient attributes. If you modify your profile factory like so:
FactoryGirl.define do factory :profile do user ignore do user_email nil # by default, we'll use the value from the user factory end title "director" bio "I am very good at things" linked_in "http://my.linkedin.profile.com" website "www.mysite.com" city "London" after(:create) do |profile, evaluator| # update the user email if we specified a value in the invocation profile.user.email = evaluator.user_email unless evaluator.user_email.nil? end endend
then you should be able to invoke it like this and get the desired result:
p = FactoryGirl.create(:profile, user_email: "test@test.com")
I haven't tested it, though.
Solved it by creating User first, and then Profile:
my_user = FactoryGirl.create(:user, user_email: "test@test.com")my_profile = FactoryGirl.create(:profile, user: my_user.id)
So, this is almost the same as in the question, split across two lines.Only real difference is the explicit access to ".id".Tested with Rails 5.