[RAILS] FactoryBot, a solution when played with a foreign key validation

Introduction

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

design

The user table is associated with the room table, and you need to enter the room_id when registering as a user.

Part of user registration test code

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).

Part of FactoryBot

room model

rooms.rb


FactoryBot.define do
  factory :room do
    Faker::Config.locale = :ja
    name { Faker::Name.first_name }
  end
end

user model

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

Cause of Rspec error

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".

Solutions

--For foreign key columns Type FactoryBot inside FactoryBot! !! ――Although it is a small point Do not describe _id.

Finally

Now you can finally proceed with the test code. After a long time, my knowledge has increased steadily!

Recommended Posts

FactoryBot, a solution when played with a foreign key validation
[Ruby on Rails] Add a column with a foreign key constraint
Precautions when generating a table with a composite key with Iciql + SQLite
How to rename a model with foreign key constraints in Rails
Add foreign key to column with migrate
How to delete data with foreign key
[Ruby On Rails] When a model unit test is performed with RSpec using FactoryBot, an error occurs because the foreign key is not entered.