LoginSignup
0
1

More than 3 years have passed since last update.

単体テストコードの実装

Last updated at Posted at 2021-01-15

私自身の備忘録として簡単にテストコードの実装をここに残しておきます。

前提条件として、今回はユーザーの新規登録の単体テストコードを作成します。
テストする内容はnickname、email、password、password_confirmationの4つをテストします。

gemの準備

まずテストするためのgemをgemfileに記述
※記述する箇所はgroup :development, :test doの中に記述すること
ここに記述するとテストする時にだけ使えるようになるため

gemfile
group :development, :test do

  gem 'rspec-rails'         #この4行を記述、テストするためのgem
  gem 'factory_bot_rails'   #この4行を記述、テンプレート的なやつを作るgem
  gem 'faker'               #この4行を記述、テキトーな文字列などを入れてくれるgem
  gem 'pry-rails'           #この4行を記述、binding.pryで処理を止めれるようにするgem

  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

上記の記述をしたら以下をターミナルで実行

ターミナル
% bundle install
% rails g rspec:install

これらのファイルが作成されたら完璧

ターミナル
create  .rspec
create  spec
create  spec/spec_helper.rb
create  spec/rails_helper.rb

.rspecのファイルに以下を記述

.rspec
--require spec_helper   #デフォルトで入ってる
--format documentation   #この行を追加

この記述は、テストコードの結果をターミナル上に可視化するための記述です。

モデルの準備

以下のコマンドでモデルの作成をします(今回はuserモデルを作成)

ターミナル
% rails g rspec:model user

これらが作成されたらおk

ターミナル
 create  spec/models/user_spec.rb
 invoke  factory_bot
 create    spec/factories/users.rb

テスト内容の洗い出し

spec/models/user_spec.rb
require 'rails_helper'

RSpec.describe User, type: :model do
  describe "ユーザー新規登録" do
    it "nicknameが空では登録できない" do
      # nicknameが空では登録できないテストコードを記述します
    end
    it "emailが空では登録できない" do
      # emailが空では登録できないテストコードを記述します
    end

    it "passwordが空では登録できない" do
      # passwordが空では登録できないテストコードを記述します
    end

    it "password_confirmationが空では登録できない" do
      # password_confirmationが空では登録できないテストコードを記述します
    end
  end
end

かる〜く解説知ってたらスルーしてよし

①describe "行いたいテストの内容" do〜end
"行いたいテストの内容"のなかに内容を記述、今回はユーザー管理機能のテストを記述

②it '条件'do〜end
'条件'の部分にテストしたい条件を記述

ちゃんとできてるか確認するためにコマンドを実行

ターミナル
% bundle exec rspec spec/models/user_spec.rb 

スクリーンショット 2021-01-15 12.23.43.png

これがターミナルに出力されたらおk

FactoryBotとFakerを使う

まずspecのディレクトリの中にfactoriesと言うディレクトリを作り、その中にuser.rbを作成する
スクリーンショット 2021-01-15 12.09.06.png

作成したusers.rbに以下を記述

spec/factories/users.rb(Fakerを使わない場合)
FactoryBot.define do
  factory :user do
    nickname              {"test"}
    email                 {"test@example"}
    password              {"000000"}
    password_confirmation {password}
  end
end
spec/factories/users.rb(Fakerを使う場合)
FactoryBot.define do
 factory :user do
   nickname              {Faker::Name.initials(number: 2)}
   email                 {Faker::Internet.free_email}
   password              {Faker::Internet.password(min_length: 6)}
   password_confirmation {password}
 end
end

これでfactorybotの準備完了!
①user_spec.rbのファイルに戻ってRSpec.describe User, type: :model doの下に以下の3行を追加
②it do〜endの処理の中に実際行う処理をそれぞれ記述する

spec/models/user_spec.rb
require 'rails_helper'

RSpec.describe User, type: :model do
  #⬇︎この3行を追加
  before do
    @user = FactoryBot.build(:user)
  end
  #⬆︎この3行を追加
  describe "ユーザー新規登録" do
    it "nicknameが空では登録できない" do
      @user.nickname = ""
      @user.valid? 
      expect(@user.errors.full_messages).to include("Nickname can't be blank") 

    end
    it "emailが空では登録できない" do
      #⬇︎実際に行う処理
      @user.email = ""  
      @user.valid? 
      expect(@user.errors.full_messages).to include("Email can't be blank") 
      #⬆︎実際に行う処理
    end

    it "passwordが空では登録できない" do
      @user.password = ""
      @user.valid? 
      expect(@user.errors.full_messages).to include("Password can't be blank")
    end

    it "password_confirmationが空では登録できない" do
       @user.password_confirmation = ""
       @user.valid?
       expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
    end
  end
end

実行しましょう!

ターミナル
% bundle exec rspec spec/models/user_spec.rb 

スクリーンショット 2021-01-15 12.23.43.png

これらが表示されたらおk
もしエラーが出てしまうならエラー箇所にbinding.pryを記述し実行しましょう!

spec/models/user_spec.rb
it "nicknameが空では登録できない" do
      @user.nickname = ""
      @user.valid? 
      binding.pry  #ここで処理が止まる
      expect(@user.errors.full_messages).to include("Nickname can't be blank") 

    end

※処理を止めてエラーの内容を確認する手順は以下の通りです

ターミナル
pry(#<RSpec::ExampleGroups::User>)> @user.valid?   #エラーが出ているかの確認
pry(#<RSpec::ExampleGroups::User>)> @user.errors.full_messages  #エラーメッセージの確認

pry(#<RSpec::ExampleGroups::User>)> exit  #railsコンソールから脱出
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1