Efficient test code

Introduction

When creating the original app, I tested it using FactoryBot and Faker, so I'll post it so I don't forget it. ** FactoryBot: ** Gem that sets the value specified for each class instance in advance ** Faker: ** Gem that generates random values ​​such as email address, personal name, password, etc. ** As a premise, it is assumed that the test file user_spec.rb has already been generated. ** **

1. Introduction and setup of gem

  1. Describe the FactoryBot and Faker Gem in group: development,: test do of Gemfile, and bundle install.

Gemfile


group :development, :test do
#Omission
  gem 'factory_bot_rails'
  gem 'faker'
end

2. Create a FactoryBot directory (①) in the spec directory, and then create a FactoryBot file (②) in it. (Example) spec / factories (①) /users.rb(②)

2. Described in the FactoryBot file (②)

Write code using ** FactoryBot ** and ** Faker ** in the file created in 1. Faker's official GitHub https://github.com/faker-ruby/faker

FactoryBot file (②)


FactoryBot.define do
  factory :user do
    name        {Faker::Name.name}
    email       {Faker::Internet.free_email}
    password    {Faker::Internet.password(min_length: 8)}
    birthday    { '2000-01-01' }
   #Omission
  end
end

3. Writing test code

Write FactoryBot.build (: user) to create an instance of User. Also, use ** before ** to create an instance before executing each test code.

user_spec.rb


require 'rails_helper'
RSpec.describe User, type: :model do
  before do
    @user = FactoryBot.build(:user)
  end

  describe 'New user registration' do
    it "Cannot register if nickname is empty" do
      @user.name = ""
      @user.valid?
      expect(@user.errors.full_messages).to include "Name can't be blank"
    end
    it "Cannot register if email is empty" do
      @user.email = ""
      @user.valid?
      expect(@user.errors.full_messages).to include "Email can't be blank"
    end
    #Omission
  end
end

Finally

It was something I learned once, but I remember it so much that I'm glad I was able to review it!

Recommended Posts

Efficient test code
RSpec test code execution
[Test code learning / output]
test
test
Memorandum (task: model test code)
Java test code method collection
[Rails] Test code using Rspec
test
test
Implementation of unit test code
[RSpec] How to write test code
[Rails] Unit test code for User model
Introduce RSpec and write unit test code
Testable code
Write code that is difficult to test
Articles and books useful for studying test code
Test Data Builder pattern ~ Improve maintainability of test code
Image column test code when ActiveStorage is introduced
RSpec-Results of reviewing the test code for'users validation'
Model unit test code to check uniqueness constraints
How to write test code with Basic authentication
Test code using mock with JUnit (EasyMock center)