-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
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
after(:build) callback should be triggered prior to save #649
Comments
@rymohr Can you provide any more context? I just wrote up this quick spec: describe "callbacks" do
before do
define_model('User') do
before_save do |user|
puts '[ActiveRecord before_save] saving user...'
end
end
FactoryGirl.define do
factory :user do
after :build do |user|
puts '[FactoryGirl after(:build)] saving user...'
end
end
end
end
it 'works' do
FactoryGirl.create :user
end
end
Which looks to be behaving correctly. Any insights? |
You'll only see this behavior when working with associations. # spec/acceptance/association_callbacks_spec.rb
require "spec_helper"
describe "callbacks" do
before do
define_model('User') do
before_save do |user|
puts 'before_save user'
end
end
define_model('Account', :user_id => :integer) do
belongs_to :user
before_save do |account|
puts 'before_save account'
end
end
FactoryGirl.define do
factory :user do
after :build do |user|
puts 'after(:build) user'
end
end
factory :account do
user
after(:build) do |account|
# account.user has already been saved
puts "after(:build) account"
end
end
end
end
it 'works' do
FactoryGirl.create :account
end
end
I would have expected this output instead:
|
@rymohr so, this is actually due to how factory_girl and ActiveRecord interact. factory_girl, when building objects, saves the associations. Because the association is saved, that's why you're seeing the order of the factory_girl callback on user, then AR (as AR is saving the associated user), and then the callbacks on the factory you're actually creating (the account). |
Is that by design or would you accept a pull that deferred saving associations? |
It does that by design; we'd run into numerous issues over the course of years by not saving associated objects when building the parent. Many stem from interacting with the associations on the built factory.
|
Hi guys sory for bringing this up, facing this same issue. |
Perhaps I'm misusing the callbacks, but shouldn't the
after(:build)
callback allow you to finalize associations and attributes prior to saving?I have a block I want to run regardless of whether
build
orcreate
is used. Here's a simplified example:If I call
FactoryGirl.create(:account, :locked => true)
it tries to save the account before the:build
callback is ever triggered.The text was updated successfully, but these errors were encountered: