FactoryGirl build strategy with nested associations
Asked Answered
S

3

6

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
Shandra answered 21/11, 2012 at 0:49 Comment(0)
F
2

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
Fouquiertinville answered 21/11, 2012 at 1:44 Comment(0)
R
1

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

Referee answered 22/1, 2018 at 14:23 Comment(0)
C
0

As @messanjah said, however for older versions (< v4.8.0) you can do the following:

association :user, :strategy => @build_strategy.class
Cryptogenic answered 26/1, 2019 at 16:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.