I have two FactoryBots => user
and post
And post has user_id
column
FactoryBot.define do
factory :user do
sequence(:name) { |n| "user#{n}" }
end
end
FactoryBot.define do
factory :post do
sequence(:title) { |n| "title#{n}" }
sequence(:user_id) { |n| n }
end
end
I want to make 10 users, and 100 posts (10posts per each user) so i tried .times method like this =>
10.times do
FactoryBot.define do
factory :post do
sequence(:title) { |n| "title#{n}" }
sequence(:user_id) { |n| n }
end
end
end
This not worked because of Factory already registered
error
FactoryBot.define do
10.times do
factory :post do
sequence(:title) { |n| "title#{n}" }
sequence(:user_id) { |n| n }
end
end
end
This not worked too.
FactoryBot.create_list(:user, 10)
10.times do
FactoryBot.create_list(:post, 10)
end
This makes FactoryBot to make post num 11, user num 11
so foriegn key error occurs.
How can i use create_list method many times?
Just i want to make is, 10 posts per 10 users.
CodePudding user response:
If you don't need to reference any of those users and/or posts afterward, then you can just 10 times create 10 posts using the same user per every 10 posts;
10.times do
create_list(:post, 10, user: create(:user))
end