Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FactoryGirl: Trouble on using the 'after_update' callback method #373

Closed
Backoo opened this issue May 6, 2012 · 1 comment
Closed

FactoryGirl: Trouble on using the 'after_update' callback method #373

Backoo opened this issue May 6, 2012 · 1 comment

Comments

@Backoo
Copy link

Backoo commented May 6, 2012

Maybe there is a bug on using FactoryGirl (or, at least, a "not common" way to handle object creation processes) with an after_update Ruby on Rails callback method as I explained here.

As you said in the Official Documentation, I tried to build my model from the rails console and I had not problem. I have trouble only when I use FactoryGirl as explained in the linked explanation.

@joshuaclayton
Copy link
Contributor

The code I gleaned from the StackOverflow issue that's actually creating the user looks like this:

FactoryGirl.create(
  :user,
  :account => FactoryGirl.create(:account)
)

In the post, you mentioned running the non-FactoryGirl version of the code and had no errors, but I want to confirm.

Without seeing your factories, the code above would essentially run:

account = Account.new
account.save! # Since this is Ruby, it'll evaluate this line as part of the hash first, before creating the user

user = User.new
user.account = account
user.save! # The hash has been evaluated and we're assigning the account created from the hash

Now, the problem I see here is that the account requires a profile, which the user creates... but only after the account tries to call save!.

It looks like all of these models are pretty tightly coupled, so it may get a bit tricky. Without seeing your factories or rest of the models, my guess is you'd want a factory like this:

factory :user do
  factory :user_with_account do
    after_create do |user|
      FactoryGirl.create(:account, :user => user)
    end
  end
end

factory :account do
  user
end

With all these interwoven models, again, it may be tricky figuring out how to set up your factories. In your case, since these records are all intertwined, you may want to look at delegation to move naming logic onto one of the models instead of having it spread across all three.

Good luck, and please post what you find here in case anyone else runs into the same issues.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants