New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
When use with create_list
, build
method returns same instance every time
#1499
Comments
I see why this is confusing, but I don't think it's a bug in factory_bot. An equivalent way of writing this in ruby that I think makes the problem a little clearer: tag = FactoryBot.build(:tag)
FactoryBot.create_list(:post, 2, tags: [tag]) We build a tag, and then we pass that one tag to If you want to execute different code for each element in the list, I believe you can do that in a block passed to FactoryBot.create_list(:post, 2) do
post.update!(tags: [FactoryBot.build(:tag)])
end |
Hmm... your example cannot pass
Should I use prevent posts = [
FactoryBot.create(:post, tags: [FactoryBot.build(:tag)]),
FactoryBot.create(:post, tags: [FactoryBot.build(:tag)])
] |
Ah right, I missed your validation (I'm used to tags being a many-to-many relationship rather than a many-to-one). In that case you might consider one of the various solutions we have for |
Description
I want to create Post record and Tag records on one transaction due to schema constraint and validation.
So, I wrote
FactoryBot.create(:post, tags: [FactoryBot.build(:tag)])
and works perfect.However when create multiple records by call
create_list
,FactoryBot.build(:tag)
returns same instance every time, so Tag records are updated multiple times.Is this designed behavior?
Reproduction Steps
A reproduction script is here.
Expected behavior
build
returns different instance every time if it is called with*_list
method.Actual behavior
build
returns same instance.System configuration
factory_bot version: 6.2.0
rails version: 6.0.3.7
ruby version: 2.7.2
The text was updated successfully, but these errors were encountered: