I've been having trouble testing Rspec with FaxtoryBot for some time due to an error. This time, I will introduce it because it was solved.
↓ Previous post How do I create a foreign key value in FactoryBot ~ (crying
The user table is associated with the room table, and you need to enter the room_id when registering as a user.
user_spec.rb
RSpec.describe User, type: :model do
describe 'user registration' do
before do
@user = FactoryBot.build(:user)
end
it 'If all items are entered, you can register' do
expect(@user).to be_valid
end
end
end
I always got an error in the part @user = FactoryBot.build (: user)
.
rooms.rb
FactoryBot.define do
factory :room do
Faker::Config.locale = :ja
name { Faker::Name.first_name }
end
end
users.rb
FactoryBot.define do
factory :user do
Faker::Config.locale = :ja
room { FactoryBot.create(:room) } #The cause of the original error 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
This is the part.
room { FactoryBot.create(:room) }(Revised)
room_id { 1 }(Before correction)
I was trying to force the room_id
, which was a foreign key, into a value of" 1 "and generate it as a FabricyBot. However, this caused a validation error. Interpreting the error is like "I can't find the foreign key".
--For foreign key columns
Type FactoryBot inside FactoryBot! !!
――Although it is a small point
Do not describe _id
.
Now you can finally proceed with the test code. After a long time, my knowledge has increased steadily!
Recommended Posts