When creating the original app, I tested it using FactoryBot and Faker, so I'll post it so I don't forget it. ** FactoryBot: ** Gem that sets the value specified for each class instance in advance ** Faker: ** Gem that generates random values such as email address, personal name, password, etc. ** As a premise, it is assumed that the test file user_spec.rb has already been generated. ** **
Gemfile
group :development, :test do
#Omission
gem 'factory_bot_rails'
gem 'faker'
end
Write code using ** FactoryBot ** and ** Faker ** in the file created in 1. Faker's official GitHub https://github.com/faker-ruby/faker
FactoryBot file (②)
FactoryBot.define do
factory :user do
name {Faker::Name.name}
email {Faker::Internet.free_email}
password {Faker::Internet.password(min_length: 8)}
birthday { '2000-01-01' }
#Omission
end
end
Write FactoryBot.build (: user) to create an instance of User. Also, use ** before ** to create an instance before executing each test code.
user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
before do
@user = FactoryBot.build(:user)
end
describe 'New user registration' do
it "Cannot register if nickname is empty" do
@user.name = ""
@user.valid?
expect(@user.errors.full_messages).to include "Name can't be blank"
end
it "Cannot register if email is empty" do
@user.email = ""
@user.valid?
expect(@user.errors.full_messages).to include "Email can't be blank"
end
#Omission
end
end
It was something I learned once, but I remember it so much that I'm glad I was able to review it!
Recommended Posts