LoginSignup
0
1

More than 3 years have passed since last update.

rails - テストコード基礎(Rspec・FactoryBot)

Last updated at Posted at 2021-03-21

テストコードの実装手順

Rspec・FactoryBotを使った基礎的なテストコード実装についてアウトプットもかねて自分用にまとめます。(今回はuserモデルの単体テストコード)


まずは実装の流れになります。

1.Gemインストール
2.Rspecの設定
3.FactoryBotの設定
4.テストコード記述ファイル作成
5.テストコード記述
6.テスト実行


1.Gemインストール

Gemfile
group :development, :test do
  gem 'rspec-rails', '~> 4.0.0' #バージョン指定
  gem 'factory_bot_rails'
end
ターミナル
bundle install

2.Rspecの設定

Rspecのインストール、ディレクトリ・ファイルを作成する

ターミナル
rails g rspec:install

テストコードの結果をターミナル上に可視化する

.rspec
--require spec_helper
--format documentation #追加

3.FactoryBotの設定

specディレクトリ内にfactoriesディレクトリを作成後

spec/factories/users.rb

FactoryBot.define do
  factory :user do
    nickname              {'test'}
    email                 {'test@com'}
    password              {'111111'}
    password_confirmation {password}
  end
end

4.テストコード記述ファイル作成

ターミナル
rails g rspec:model user

5.テストコード記述

spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
  before do
    @user = FactoryBot.build(:user) #インスタンス生成
  end

  describe 'ユーザー新規登録' do 
    it 'nicknameが空では登録できない' do
      @user.nickname = ''
      @user.valid?
      expect(@user.errors.full_messages).to include "Nickname can't be blank"
    end
  end
end

6.テスト実行

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

おまけ

エラーメッセージの日本語化

以下の手順でエラーメッセージを日本語にすることもできる。

1.Gemインストール

config/application.rb
module Pictweet
 class Application < Rails::Application
   # 日本語の言語設定
   config.i18n.default_locale = :ja #追加
 end
end
Gemfile
gem 'rails-i18n'
ターミナル
bundle install

2.各種ファイルの作成、記述

  • config/localesディレクトリにdevise.ja.ymlファイルを作成
  • devise-i18nから記述をコピーして貼り付け
config/locales/devise.ja.yml
ja:
  activerecord:
    attributes:
      user:
        confirmation_sent_at: パスワード確認送信時刻
        confirmation_token: パスワード確認用トークン
        confirmed_at: パスワード確認時刻
        created_at: 作成日
        current_password: 現在のパスワード
        current_sign_in_at: 現在のログイン時刻
        current_sign_in_ip: 現在のログインIPアドレス
        email: Eメール
〜〜〜〜〜〜〜〜〜〜 以下略 〜〜〜〜〜〜〜〜〜〜〜〜〜〜
  • config/localesディレクトリにja.ymlファイルを作成
config/locales/ja.yml
ja:
 activerecord:
   attributes:
     user:
       nickname: ニックネーム
     tweet:
       text: テキスト
       image: 画像

これで日本語化は完了です、あとはテストコードのエラーメッセージ部分を書き換えればテストも通ります。

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