I'm going to introduce Rspec and write test code. The command uses the command of the docker environment.
group :development, :test do
gem 'rspec-rails'
gem 'factory_bot_rails'
gem 'faker', "~> 2.8"
end
docker-compose run web bundle install
docker-compose build
Installation is complete.
docker-compose run webrails g rspec:install
When the above command is executed, the following file is generated.
create .rspec
create spec
create spec/spec_helper.rb
create spec/rails_helper.rb
.rspc
--format documentation
spec/models/user_spec.rb
require 'rails_helper'
describe User do
describe '#create' do
it "username and email,password and password_Being able to register if confirmation exists" do
user = build(:user)
expect(user).to be_valid
end
it "Cannot register without username" do
user = build(:user, username: nil)
user.valid?
expect(user.errors[:username]).to include("can't be blank")
end
it "Cannot register without email" do
user = build(:user, email: nil)
user.valid?
expect(user.errors[:email]).to include("can't be blank")
end
it "Cannot register without password" do
user = build(:user, password: nil)
user.valid?
expect(user.errors[:password]).to include("can't be blank")
end
it "password even if password exists_Cannot register without confirmation" do
user = build(:user, password_confirmation: "")
user.valid?
expect(user.errors[:password_confirmation]).to include("doesn't match Password")
end
it "Cannot register if there are duplicate emails" do
user = create(:user)
another_user = build(:user, email: user.email)
another_user.valid?
expect(another_user.errors[:email]).to include("has already been taken")
end
it "If the password is 6 characters or more, you can register" do
user = build(:user, password: "000000", password_confirmation: "000000")
expect(user).to be_valid
end
it "Cannot register if password is 5 characters or less" do
user = build(:user, password: "00000", password_confirmation: "00000")
user.valid?
expect(user.errors[:password]).to include("is too short (minimum is 6 characters)")
end:grin:
end
end
spec/factories/users.rb
FactoryBot.define do
factory :user do
username {"aaa"}
password {"000000"}
password_confirmation {"000000"}
sequence(:email) {Faker::Internet.email}
end
end
docker-compose run web bundle exec rspec
8 examples, 0 failures
If so, the test has passed successfully.
This time, I entered the test using Rspec. We will also test the controller in the future. Thank you for reading to the end: grin:
Recommended Posts