Is it possible to preserve the build strategy when I have a factory for a model that has an association to a second model, which itself has an association to a third model?
In the example below, a Post is associated with a User, and a User is associated with a City. Even when :strategy => :build
is used for all associations, post.user
and post.user.city
end up getting saved to the database. In the interests of a speedy test suite, can I prevent these database writes from happening?
Factory.define do
factory :user do
name "A User"
association :city, :strategy => :build
end
factory :city do
name "A City"
end
factory :post do
title "A Post"
body "Some text here"
association :user, :strategy => :build
end
end
post = FactoryGirl.build(:post)
post.new_record? # True
post.user.new_record? # False
post.user.city.new_record? # False
Have you tried the alternative block syntax?
Factory.define do
factory :user do
name "A User"
city { |city| city.association :city, :strategy => :build }
end
factory :city do
name "A City"
end
end
It looks like FactoryBot (formerly FactoryGirl
) added use_parent_strategy
as a configuration option in v4.8.0. It is turned off by default, to turn it on add the following to your spec/rails_helper
:
FactoryGirl.use_parent_strategy = true
Relevant pull request on the factory_bot
repo: https://github.com/thoughtbot/factory_bot/pull/961
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With