[Unit test code] Even though I have a foreign key, I am told "Please enter XX"

problem

I did a test called "when comments can be saved" with unit test code. At that time, the foreign keys created by FactoryBot, skill_id and user_id, existed, but for some reason they were said to be empty.

Error statement


  1)Comment Posting When comment posting is successful You can register if there is a comment
     Failure/Error: expect(@comment).to be_valid
       expected #<Comment id: nil, text: "v5tycc16e03hixch09y3661diocp6t5mwqj11r26gbjnptc0ty...", skill_id: 2, user_id: 1, created_at: nil, updated_at: nil> to be valid, but got errors:Please enter User,Please enter Skill
     # ./spec/models/comment_spec.rb:11:in `block (4 levels) in <top (required)>'

Finished in 0.78208 seconds (files took 6.7 seconds to load)
3 examples, 1 failure

Conclusion

When checking the validation of foreign keys, get the value by accessing the database with create instead of build. Apparently, skill_id and user_id existed, but because of the foreign key constraint in the migration file, those values had to be brought from another table.

Construction

image.png

before

factorybot


FactoryBot.define do
  factory :comment do
    text { Faker::Lorem.characters(number: 100) }
    user_id { 1 }
    skill_id { 2 }
  end
end

comment_spec.rb


require 'rails_helper'
RSpec.describe Comment, type: :model do
  describe 'Post a comment' do
  before do
    @comment = FactoryBot.build(:comment)
  end

    context 'When comment posting goes well' do
      it 'You can register if there is a comment' do
        expect(@comment).to be_valid
      end
    end
...

after

factorybot


FactoryBot.define do
  factory :comment do
    text { Faker::Lorem.characters(number: 100) }
    association :user
    association :skill
  end
end

comment_spec.rb


require 'rails_helper'
RSpec.describe Comment, type: :model do
  describe 'Post a comment' do
  before do
    @comment = FactoryBot.create(:comment)
  end

    context 'When comment posting goes well' do
      it 'You can register if there is a comment' do
        expect(@comment).to be_valid
      end
    end
...

Recommended Posts

[Unit test code] Even though I have a foreign key, I am told "Please enter XX"
I got an ActionController :: MissingExactTemplate even though I have a file
I want to write a unit test!
I get a javax.mail.AuthenticationFailedException even though I haven't authenticated.