Implementation of unit test code

I'll leave a quick test code implementation here as a reminder of myself.

As a prerequisite, this time we will create a unit test code for the new registration of the user. There are four things to test: nickname, email, password, and password_confirmation.

Gem preparation

First, write the gem to test in the gemfile * Describe the part to be described in group: development,: test do. If you write it here, you can use it only when testing.

gemfile


group :development, :test do

  gem 'rspec-rails'         #A gem for writing and testing these 4 lines
  gem 'factory_bot_rails'   #A gem that describes these 4 lines and creates a template-like one
  gem 'faker'               #A gem that describes these 4 lines and puts a text string etc.
  gem 'pry-rails'           #Describe these 4 lines, binding.A gem that allows pry to stop processing

  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

After writing the above, execute the following in the terminal

Terminal


% bundle install
% rails g rspec:install

Perfect once these files are created

Terminal


create  .rspec
create  spec
create  spec/spec_helper.rb
create  spec/rails_helper.rb

Write the following in the .rspec file

.rspec


--require spec_helper   #Included by default
--format documentation   #Add this line

This description is for visualizing the result of the test code on the terminal.

Model preparation

Create a model with the following command (create a user model this time)

Terminal


% rails g rspec:model user

Once these are created

Terminal


 create  spec/models/user_spec.rb
 invoke  factory_bot
 create    spec/factories/users.rb

Clarification of test contents

spec/models/user_spec.rb


require 'rails_helper'

RSpec.describe User, type: :model do
  describe "New user registration" do
    it "Cannot register if nickname is empty" do
      #Write test code that cannot be registered if nickname is empty
    end
    it "Cannot register if email is empty" do
      #Write a test code that cannot be registered if email is empty
    end

    it "Cannot register if password is empty" do
      #Write a test code that cannot be registered if the password is empty
    end

    it "password_Cannot register if confirmation is empty" do
      # password_Write a test code that cannot be registered if confirmation is empty
    end
  end
end

If you know the explanation, you can go through it.

① describe "Content of the test you want to do" do ~ end Describe the content in "Content of the test you want to perform", this time describe the test of the user management function

② it'condition' do ~ end Describe the condition you want to test in the'condition'part

Execute the command to check if it is done properly

Terminal


% bundle exec rspec spec/models/user_spec.rb 

スクリーンショット 2021-01-15 12.23.43.png

If this is output to the terminal

Use FactoryBot and Faker

First, create a directory called factories in the spec directory, and create user.rb in it. スクリーンショット 2021-01-15 12.09.06.png

Describe the following in the created users.rb

spec/factories/users.rb (when not using Faker)


FactoryBot.define do
  factory :user do
    nickname              {"test"}
    email                 {"test@example"}
    password              {"000000"}
    password_confirmation {password}
  end
end

spec/factories/users.rb (when using Faker)


FactoryBot.define do
 factory :user do
   nickname              {Faker::Name.initials(number: 2)}
   email                 {Faker::Internet.free_email}
   password              {Faker::Internet.password(min_length: 6)}
   password_confirmation {password}
 end
end

Now the factorybot is ready! ① Go back to the user_spec.rb file and add the following 3 lines under RSpec.describe User, type:: model do (2) Describe the actual processing to be performed in the processing of it do to end.

spec/models/user_spec.rb


require 'rails_helper'

RSpec.describe User, type: :model do
  #⬇︎ Add these 3 lines
  before do
    @user = FactoryBot.build(:user)
  end
  #⬆︎ Add these 3 lines
  describe "New user registration" do
    it "Cannot register if nickname is empty" do
      @user.nickname = ""
      @user.valid? 
      expect(@user.errors.full_messages).to include("Nickname can't be blank") 

    end
    it "Cannot register if email is empty" do
      #⬇︎ Actual processing
      @user.email = ""  
      @user.valid? 
      expect(@user.errors.full_messages).to include("Email can't be blank") 
      #⬆︎ Actual processing
    end

    it "Cannot register if password is empty" do
      @user.password = ""
      @user.valid? 
      expect(@user.errors.full_messages).to include("Password can't be blank")
    end

    it "password_Cannot register if confirmation is empty" do
       @user.password_confirmation = ""
       @user.valid?
       expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
    end
  end
end

Let's do it!

Terminal


% bundle exec rspec spec/models/user_spec.rb 

スクリーンショット 2021-01-15 12.23.43.png

When these are displayed, k If you get an error, write binding.pry in the error area and execute it!

spec/models/user_spec.rb


it "Cannot register if nickname is empty" do
      @user.nickname = ""
      @user.valid? 
      binding.pry  #Processing stops here
      expect(@user.errors.full_messages).to include("Nickname can't be blank") 

    end

Terminal


pry(#<RSpec::ExampleGroups::User>)> @user.valid?   #Check if there is an error
pry(#<RSpec::ExampleGroups::User>)> @user.errors.full_messages  #Check the error message

pry(#<RSpec::ExampleGroups::User>)> exit  #Escape from the rails console

Recommended Posts

Implementation of unit test code
Significance of existence of unit test (self-discussion)
Introduce RSpec and write unit test code
Implementation of GKAccessPoint
Efficient test code
[Implementation] Eliminate the ominous smell of code
Test Data Builder pattern ~ Improve maintainability of test code
RSpec-Results of reviewing the test code for'users validation'
Automatic creation of Java unit test result report
Implementation of flash messages
Implementation of search function
Java Unit Test Library-Artery-Sample
Applied implementation of chat-space
[Test code learning / output]
Implementation of pagination function
Unit test with Junit.
Json Request in Unit Test of Controller using MockMvc
RSpec unit test code creation procedure (login user creation Ver.)
About method matchers used in model unit test code (RSpec)
Rails implementation of ajax removal
[Swift] Simple implementation of UIImageView
Implementation of sequential search function
[Swift] Implementation of ultra-simple billing
[IntelliJ IDEA] Perform Unit Test
Implementation of like function (Ajax)
[Rails 6] Implementation of search function
Implementation of image preview function
Memorandum (task: model test code)
Introduction to Micronaut 2 ~ Unit test ~
About types of code coverage
Implementation of XLPagerTabStrip with TabBarController
Java test code method collection
[Rails] Implementation of category function
Unit test architecture using ArchUnit
[Rails] Test code using Rspec
Implementation of gzip in java
[Rails] Implementation of tutorial function
[Rails] Implementation of like function
Implementation of tri-tree in Java
Implementation of HashMap in kotlin
I checked the automatic unit test creation tool (end of 2019 version)
Sample code to unit test a Spring Boot controller with MockMvc
I tested how to use Ruby's test / unit and rock-paper-scissors code.
Password dummy data generation notes in Rails model unit test code
[Rails] Implementation of user logic deletion
[Rails] Implementation of CSV import function
[Rails] Asynchronous implementation of like function
Java Unit Test Library-Artery-ArValidator Validates Objects
[Rails] Implementation of image preview function
Implementation of ls command in Ruby
Write test code in Spring Boot
Easy implementation of Android file browsing
Java Unit Test Library-Artery-Current Date Judgment
[Rails] About implementation of like function
[Rails] Implementation of user withdrawal function
Java 15 implementation and VS Code preferences
[Rails] Implementation of CSV export function
Implementation of asynchronous processing in Tomcat
Implementation of validation using regular expressions
[Rails5] Rspec -Unit test when nesting-
About app testing RSpec (unit test)