[RSpec] Unit test (using gem: factory_bot)

Introducing RSpec

Be careful not to duplicate web-console

Gemfile


gem 'rspec-rails'

group :development do
  gem 'web-console'
end

After bundle install`` rails g rspec: install

Edit the .rspec file to make it easier to read:

.rspec


--format documentation

At this point, let's check if RSpec works properly. bundle exec rspec

Terminal


If it works normally, it will be like this
No examples found.


Finished in 0.00031 seconds (files took 0.19956 seconds to load)
0 examples, 0 failures

File to be created

.rspec spec spec/spec_helper.rb Like rails_helper.rb, it is a file that writes common settings for RSpec, but this is used when using RSpec without Rails.

spec/rails_helper.rb It is a file to write common settings when using RSpec in Rails. Apply common settings and methods by reading this file in each test file

Introduced factory_bot_rails

Gemfile


group :development, :test do
  #abridgement
  gem 'rspec-rails'
  gem 'factory_bot_rails'
end

** Creating a file ** Create a Ruby file with the plural file name of the created instance Created this time so that it becomes spec / factories / ʻusers.eb`.

** Edit file ** Make it easy to instantiate or save to DB by a specific method in the spec file

user.rb


FactoryBot.define do

  factory :user do
    nickname              {"abe"}
    email                 {"[email protected]"}
    password              {"00000000"}
    password_confirmation {"00000000"}
  end

end

factory_bot basic methods

** build method ** Create an instance of the class name taken as a symbol type as an argument based on the description of factory_bot

Example


#factory_When not using a bot
user = User.new(nickname: "abe", email: "[email protected]", password: "00000000", password_confirmation: "00000000")
#factory_When using a bot
user = FactoryBot.build(:user)

** create method ** It works almost the same as build, but in the case of create, the value is saved in the test DB. The test is executed once, and the contents of the test DB are rolled back each time it is completed.

Example


#The created instance is saved in the DB
user = FactoryBot.create(:user)

Omission of factory_bot notation

When creating an instance with factory_bot, you can omit the description of FactoryBot of the class that is the receiver.

rails_helper.rb


#abridgement
RSpec.configure do |config|
  #Added the following description
  config.include FactoryBot::Syntax::Methods

  #abridgement

end

Write test code for your model

ʻUser modeltest code ** Create spec file ** File naming conventioncorresponding class name_spec.rb`

Create so that it becomes spec / models / user_spec.rb.

user_spec.rb


require 'rails_helper'
describe User do
  describe '#create' do
    it "Cannot register without nickname" do
      user = build(:user, nickname: "")
      user.valid?
      expect(user.errors[:nickname]).to include("can't be blank")
    end
  end
end

Code description

describe describe creates a set of tests immediately after do ~ end. In the "" that follows the describe, write a description of the group.

** it and example ** it represents a set of working test code called an example. Write a description of the example in the "" that follows it.

** Expectation ** It is the formula that is actually evaluated. Write between it do ~ end. In the above formula, ʻexpect (user.errors [: nickname]). To include ("can't be blank") `is the expectation.

** Matcha ** Shows the conditions under which the test will succeed in the expectation.

Method

valid? Check "Is it in a state where it cannot be saved due to validation?" The return value of the method is true / false

errors If you use the errors method for an instance that uses the valid? method, check why it cannot be saved if it cannot be saved due to validation.

Matcha

include You can check if the value taken as an argument is included in the array that is the argument of expect Duplicate pattern: has already been taken Empty pattern: can't be blank Insufficient character pattern: is too short Pattern with too many characters: is too long

be_valid It passes when the instance set as the argument of expect clears all validations. Example below

sample_spec.rb


it "Can be registered if nickname is 6 characters or less" do
  user = build(:user, nickname: "aaaaaa")
  expect(user).to be_valid
end

eq If they are equal, they will pass. Example below

sample_spec.rb


describe "sum" do
  it "1 +1 becomes 2" do
    expect(1 + 1).to eq 2
  end
end

Recommended Posts

[RSpec] Unit test (using gem: factory_bot)
Unit test architecture using ArchUnit
[Rails / RSpec] Write Model test (using Shoulda Matchers / FactoryBot)
I tried unit testing Rails app using RSpec and FactoryBot
Image upload using CarrierWave ~ Rspec test ~
[Rails5] Rspec -Unit test when nesting-
About app testing RSpec (unit test)
Let's unit test with [rails] Rspec!
Json Request in Unit Test of Controller using MockMvc
[Rails] From test preparation to model unit testing [RSpec]
RSpec test code execution
[Rails] Test of star evaluation function using Raty [Rspec]
Introduction to RSpec 1. Test, RSpec
How to unit test with JVM with source using RxAndroid
RSpec unit test code creation procedure (login user creation Ver.)
Unit test code for a model using RSpec, which has a little peculiarity ~ User registration
Java Unit Test Library-Artery-Sample
[Rails] Test with RSpec
Test Nokogiri with Rspec.
Unit test with Junit.
How to dynamically write iterative test cases using test / unit (Test :: Unit)
[RSpec] Use WebMock to test logic using an external API
I'm writing test code using RSpec, but it doesn't work
Create multiple instances together from FactoryBot with RSpec using create_list
[RSpec] Let's use FactoryBot [Rails]
[IntelliJ IDEA] Perform Unit Test
Test Active Strage with RSpec
Introduction to Micronaut 2 ~ Unit test ~
Logical deletion using Gem paranoia
Test GraphQL resolver with rspec
Implementation of unit test code
[Rails] About Rspec response test
[Ruby On Rails] When a model unit test is performed with RSpec using FactoryBot, an error occurs because the foreign key is not entered.