After introducing RSpec, until you start writing unit test code for your model

Introduction

For the flow up to the introduction of RSpec, click here [https://qiita.com/TerToEer_sho/items/472e14df6fbb8e83ebf9)

flow

  1. Factory Bot preparation
  2. Generate a file that describes the test code
  3. Description type

1. Factory Bot preparation

Prepare directories and files. ex) For user model FactoryBot, spec / factories / users.rb

spec/factories/users.rb



FactoryBot.define do
  factory :user do
    email {Faker::Internet.free_email} #Example
    #Below, describe the necessary Faker in the same way
  end
end

The: user part is used when calling Faker in spec / models / user_spec.rb.

For details on how to use Faker, go to Faker's GitHub

2. Generate a file that describes the test code

At the terminal

rails g rspec:model model name

With this command spec / models / model name_spec.rb File is generated.

From the beginning in the file

spec/models/user_spec.rb


RSpec.describe User, type: :model do
  pending "add some examples to (or delete) #{__FILE__}" #Delete this line
end

It contains code like this. You can delete the code on the second line. (In the above example, user is specified as the model name)

3. Description type

spec/models/user_spec.rb


RSpec.describe User, type: :model do
  describe 'What to test (Example) New user registration' do
    before do
      @user = FactoryBot.build(:user) #Taking the user model as an example, call user's FactoryBot
    end
    it "Specific test items (example) Email address is required" do 
    end
  end
end

(Similarly, in the above example, user is specified as the model name.)

.build (: user) ←: user is called from FactoryBot.

Put an example between ʻit and do. Write the code between do ~ end`.

Recommended Posts

After introducing RSpec, until you start writing unit test code for your model
[Rspec] Flow from introducing Rspec to writing unit test code for a model
Unit test code for a model using RSpec, which has a little peculiarity ~ User registration
About method matchers used in model unit test code (RSpec)
Introduce RSpec and write unit test code
Model unit test code to check uniqueness constraints
[Rails] From test preparation to model unit testing [RSpec]
RSpec unit test code creation procedure (login user creation Ver.)
What to do if you get a "302" error in your controller unit test code in Rails
I'm writing test code using RSpec, but it doesn't work