Model unit test code to check uniqueness constraints

Introduction

This is an addition to the post the other day. Unit test code of model using RSpec which is a little peculiar ~ User registration

Test code to verify uniqueness constraints

RSpec.describe School, type: :model do
  describe 'School registration' do
    before do
      @school = FactoryBot.build(:school)
    end
  it 'The same school name cannot be registered' do
    @school.save #← Point ①
    another_school = FactoryBot.build(:school) #← Point ②
    another_school.name = @school.name #← Point ③
    another_school.valid?
    expect(another_school.errors.full_messages).to include("The school name already exists")
  end
end

A little commentary

Point ①

Save FactoryBot.build (: school) as @ school.save first.

Point ②

Create another as another (name is free).

Point ③

Make the newly generated value at point ② and the previously saved value at point ① the same.

Recommended Posts

Model unit test code to check uniqueness constraints
[Rspec] Flow from introducing Rspec to writing unit test code for a model
[Rails] From test preparation to model unit testing [RSpec]
Memorandum (task: model test code)
Introduction to Micronaut 2 ~ Unit test ~
Implementation of unit test code
About method matchers used in model unit test code (RSpec)
[RSpec] How to write test code
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
Introduce RSpec and write unit test code
I want to write a unit test!
What is the model test code testing
Write code that is difficult to test
How to write test code with Basic authentication
Unit test code for a model using RSpec, which has a little peculiarity ~ User registration
Efficient test code
[Rails / Uniqueness constraint] How to check model validation on the console / Uniqueness constraint for multiple columns
How to write a unit test for Spring Boot 2
How to unit test with JVM with source using RxAndroid
RSpec unit test code creation procedure (login user creation Ver.)
To implement, write the test and then code the process
How to check CircleCI code and automatically deploy to Heroku
How to dynamically write iterative test cases using test / unit (Test :: Unit)
What to do if you get a "302" error in your controller unit test code in Rails