This time, I will summarize the flow of writing the unit test code of the user model by introducing rspec.
Along with that, FactoryBot and Faker were also introduced and implemented, so I will describe them.
It is a tool that creates data for testing.
You can randomly add content to the data created by FactoryBot.
As a point, pay attention to the location of the Gemfile. Not at the bottom.
gemfile
group :development, :test do
gem 'rspec-rails'
gem 'factory_bot_rails'
gem 'faker'
end
after this $ bundle install To do.
Next, execute the command to generate a directory etc. for writing RSpec.
Terminal
rails g rspec:install
This should generate directories and files.
Next, let's write the following in .rspec.
.rspec
--require spec_helper
--format documentation
Finally, let's generate a FactoryBot file. Create your own factories directory in the spec directory, and this time create users.rb.
Now the preparation is OK.
Let's define each value in the file created earlier.
spec/factories/users.rb
FactoryBot.define do
factory :user do
nickname {Faker::Name.last_name}
email {Faker::Internet.free_email}
password = Faker::Internet.password(min_length: 6)
password {password}
password_confirmation {password}
family_name { "Yamada" }
first_name {"Taro"}
read_family {"Yamada"}
read_first {"Taro"}
birth {Faker::Date.between(from: '1930-01-01', to: '2015-12-31')}
end
end
The point here is that some use Faker and some do not. Faker can only randomly generate alphanumeric characters. Therefore, family_name etc. were priced appropriately this time.
There seems to be a gem that can create dummy data in Japanese, but this time I gave it up.
First of all, as a preparation, generate a file to write the test code with the command.
Terminal
rails g rspec:model user
Then spec/models/user_spec.rb Will be generated.
Let's write the unit test code there.
user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
describe '#create' do
before do
@user = FactoryBot.build(:user)
end
it "Cannot register if nickname is empty" do
@user.nickname = nil
@user.valid?
expect(@user.errors.full_messages).to include("Nickname can't be blank")
end
it "Cannot register if email is empty" do
@user.email = nil
@user.valid?
expect(@user.errors.full_messages).to include("Email can't be blank")
end
it "You cannot register if the email is not unique" do
@user.save
another_user = FactoryBot.build(:user, email: @user.email)
another_user.valid?
expect(another_user.errors.full_messages).to include("Email has already been taken")
end
---abridgement---
end
end
Since it is long, I omitted it considerably, but I will describe it like this.
The point is Before do is to properly define FactoryBot data with instance variables. I forgot this and @user became nil and got lost once (de amateur)
If you can write it well, at the terminal
Terminal
bundle exec rspec spec/models/user_spec.rb
Enter the command and run the test.
Recommended Posts