thoughtbot / factory_bot

A library for setting up Ruby objects as test data.
https://thoughtbot.com
MIT License
7.89k stars 2.6k forks source link

Factory with explicitly specified `parent` has broken associations #1638

Closed varg90 closed 2 months ago

varg90 commented 2 months ago

Description

When we explicitly assign the factory parent, its associations lose the anchor to the instance. I know that I can just do

FactoryBot.define do
  factory :post do
    user

    factory :approved_post
  end
end

But I prefer to keep my factories in separated files for different models. I think this feature might not work with associations as expected.

Reproduction Steps

class Post < ApplicationRecord
end

class ApprovedPost < Post
  self.table_name = 'approved_posts'
end
FactoryBot.define do
  factory :post do
    user
  end
end
FactoryBot.define do
  factory :approved_post, parent: :post
end
>> include FactoryBot::Syntax::Methods
>> post = create(:post)
>> approved_post = create(:approved_post)

Expected behavior

>> post.user.post == post
=> true
>> approved_post.user.approved_post == post
=> true

Actual behavior

>> post.user.post == post
=> true
>> approved_post.user.approved_post == post
=> false

System configuration

factory_bot (6.2.0):
rails (6.1.7.6):
ruby '2.7.5':

varg90 commented 2 months ago

It inherits the parent class, so I just defined it with class: 'ApprovedPost' and it solves the problem.