Factory with explicitly specified `parent` has broken associations
varg90 opened this issue · comments
Alex Kuhn commented
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':
Alex Kuhn commented
It inherits the parent class, so I just defined it with class: 'ApprovedPost'
and it solves the problem.