Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FactoryGirl build strategy with nested associations

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
like image 862
mattjbray Avatar asked Nov 21 '12 00:11

mattjbray


2 Answers

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
like image 121
Andrew Hubbs Avatar answered Sep 27 '22 21:09

Andrew Hubbs


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

like image 35
messanjah Avatar answered Sep 27 '22 22:09

messanjah