How to write an external reference key in FactoryBot

Introduction

When I was writing the test code in Rails, even if I filled in all the necessary items, I got an error about the description of the externally referenced column, so I summarized how to describe the external reference key in FactoryBot.

Prerequisites

In the User model and Article model as shown in the ER diagram below, consider the case where the user_id of the Article model is externally referenced. Also, as shown below, User's FactoryBot is already defined. ER.png

user.rb


#User's FactoryBot
FactoryBot.define do
  factory :user do
    nickname               {Faker::Name.name}
    email                  {Faker::Internet.email}
    password               {Faker::Internet.password}
    password_confirmation  {password}
    last_name              {"Post"}
    first_name             {"Taro"}
  end
end

Test code to run

article_spec.rb


#Test code to run in Article
require 'rails_helper'

describe Article do
  before do
    @article = FactoryBot.build(:article)
  end

  describe 'Article new post' do
    context 'When new posts work' do
      it 'You can register if all the necessary items exist' do
        expect(@article).to be_valid
      end
    end
    context 'When new posts don't work' do
      it 'Cannot register if title is empty' do
        @article.title = ""
        @article.valid?
        expect(@article.errors.full_messages).to include("Title can't be blank")
      end
    end
  end
end

As mentioned above, consider the case of unit test execution of the Article model. This time, for the sake of simplicity, when all the necessary items are described as a normal system, consider only the case where the title column is empty as an abnormal system.

Code in error

article.rb


#Article FactoryBot
FactoryBot.define do
  factory :article do
    title            {"AIUEO"}
    prefecture_id    {Faker::Number.within(range: 1..10)}
    distance         {Faker::Number.within(range: 10..500)}
    content          {"Aiue Okakikukeko"}
    user_id          {1}
  end
end

At first, I defined FactoryBot of Article in the above article.rb and ran the test of article_spec.rb, but I got an error of'User must exist'in the part of it'Can be registered if all necessary items exist'. It happened. From this, you can see that the external reference cannot be made only by the description of user_id {1} in article_rb.

Solution 1

article_spec.rb


#Article FactoryBot
FactoryBot.define do
  factory :article do
    title            {"AIUEO"}
    prefecture_id    {Faker::Number.within(range: 2..48)}
    distance         {Faker::Number.within(range: 10..500)}
    content          {"Aiue Okakikukeko"}
    user             {FactoryBot.create(:user)}
  end
end

Changed the part that was set as user_id {1} to the instance created by User's FactoryBot. This made it externally visible in the articles table, and the test code in article_spec.rb ran successfully.

Solution 2

article_spec.rb


#Article FactoryBot
FactoryBot.define do
  factory :article do
    title            {"AIUEO"}
    prefecture_id    {Faker::Number.within(range: 2..48)}
    distance         {Faker::Number.within(range: 10..500)}
    content          {"Aiue Okakikukeko"}
    association      :user
  end
end

Next, I changed the part that was user_id {1} to the description of association: user. Again, the test code in article_spec.rb ran correctly.

Summary

When describing an external reference key in FactoryBot, I learned that it is not possible to correctly externally reference by simply describing numbers directly such as user_id {1}, and it is necessary to describe solutions ① and ②.

Recommended Posts

How to write an external reference key in FactoryBot
How to insert an external library
[Rails] How to write user_id (foreign key) in strong parameter
How to write an RSpec controller test
[JavaFX] How to write Eclipse permissions in build.gradle
How to write offline 15th reference question answer
How to write an if statement to improve readability-java
JUnit 5: How to write test cases in enum
How to solve an Expression Problem in Java
How to build an executable jar in Maven
How to write Java String # getBytes in Kotlin?
Notes on how to write comments in English
How to write Rails
How to write dockerfile
How to write docker-compose
How to write Mockito
How to write migrationfile
How to make an image partially transparent in Processing
Javaer tries to summarize how to write properties in C #
How to use an array for a TreeMap key
[Ruby on Rails] How to write enum in Japanese
How to write to apply gem Pagy (pagination) to an array
How to write a date comparison search in Rails
How to write a core mod in Minecraft Forge 1.15.2
[Rails] How to display an image in the view
How to create an application
How to write good code
How to write java comments
[Refactoring] How to write routing
[Note] How to write Dockerfile/docker-compose.yml
How to write Junit 5 organized
How to write Rails validation
How to write Rails seed
How to handle an instance
How to write Rails routing
How do you create foreign key values ​​in FactoryBot ~ (crying
How to pass an object to Mapper in MyBatis without arguments
How to use a foreign key with FactoryBot ~ Another solution
[Swift] Table View Cell, how to jump to an external URL
How to change a string in an array to a number in Ruby
How to retrieve the hash value in an array in Ruby
What happened in "Java 8 to Java 11" and how to build an environment
[Rails5] japanMap link How to write parameters in js.erb file
[Ruby] How to batch convert strings in an array to numbers
How to use Lombok in Spring
How to find May'n in XPath
[Ruby] How to count even or odd numbers in an array
How to hide scrollbars in WebView
How to iterate infinitely in Ruby
Studying Java # 6 (How to write blocks)
How to run Ant in Gradle
How to master programming in 3 months
How to learn JAVA in 7 days
Baseball ball count (how to write)
How to output the value when there is an array in the array
How to install Bootstrap in Ruby
How to write ruby if in one line Summary by beginner
How to write a ternary operator
How to use InjectorHolder in OpenAM
[Rails] How to write exception handling?
How to write Java variable declaration