This time I will write down the procedure to introduce Rspec when writing test code instead of a memorandum.
Introduce 3 types of gems used in the test.
Describe in the process of group: development,: test do ~ end
.
Gemfile
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
gem 'rspec-rails
gem 'factory_bot_rails'
gem 'faker'
end
After writing, do bundle install
and restart the local server.
Terminal
% rails g rspec:install
.rspec
--require spec_helper
--format documentation # =>Postscript
Set if you want to display the test error message in English.
RSpec.configure do |config|
Added above.
spec/rails_helper.rb
#Omission
I18n.locale = "en"
RSpec.configure do |config|
#Omission
--Create a factories
directory inside the spec directory.
--And create a file in it to generate a test FactoryBot.
--The name is model name s.rb
. This time I want to write the test code of the user model, so I will use ʻusers.rb`.
spec/factories/users.rb
FactoryBot.define do
factory :user do
name {Faker::Name}
email {Faker::Internet.free_email}
password = Faker::Internet.password(min_length: 6)
password {password}
password_confirmation {password}
end
end
Terminal (console)
pry(main)> FactoryBot.create(:user)
--I got an error with the above command. At that time, it seems that the cause is that Spring is running behind the scenes, so use the spring stop
command to stop Spring.
--If you see Spring stopped.
, Spring has been stopped normally.
--And then type FactoryBot.create (: user)
again on the console to see the creation.
#Exit the console with exit
% spring stop
--The following command will generate a file called spec / models / user_spec.rb
.
Terminal
% rails g rspec:model user
I will write test code more and more like this.
spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
pending "add some examples to (or delete) #{__FILE__}"# =>The original description is deleted
describe 'New user registration' do
before do
@user = FactoryBot.build(:user)
end
it "name, email, password, password_If all confirmations are entered, it will be saved" do
expect(@user).to be_valid
end
end
end
Run the following code.
Terminal
% bundle exec rspec spec/models/user_spec.rb
https://rubydoc.info/gems/faker/1.3.0/frames http://railscasts.com/episodes/126-populating-a-database https://github.com/takeyuweb/trygems/blob/master/try-faker/faker.md
Faker::Japanese https://github.com/tily/ruby-faker-japanese
Recommended Posts