The other day, I posted a case where the value of a foreign key is used in FactoryBot. When I was investigating after that, there was another method, so I will introduce it. If anything, this one is easier. FactoryBot, solution when played by foreign key validation
FactoryBot.define do
factory :user do
Faker::Config.locale = :ja
room { FactoryBot.create(:room) } #The point is here
email { Faker::Internet.free_email }
nickname { Faker::Name.last_name }
password = Faker::Internet.password(min_length: 6)
password { password }
password_confirmation { password }
end
end
FactoryBot.define do
factory :user do
Faker::Config.locale = :ja
#Removed faker in room
email { Faker::Internet.free_email }
nickname { Faker::Name.last_name }
password = Faker::Internet.password(min_length: 6)
password { password }
password_confirmation { password }
association :room #β Addendum
end
end
Like when writing an association in a model
association: model name of the foreign key
Just do.
When using FactoryBot as a foreign key, if you obediently set association: model name of the foreign key
, it will automatically associate it with the foreign key and generate test information.
Recommended Posts