LoginSignup
0
0

More than 1 year has passed since last update.

モデル単体テストコードの書き方

Posted at

はじめに

プログラミング初学者のため、自分の理解できている範囲内で言語化しています。
何か間違っている情報や改善点などありましたら、コメントいただけますと幸いです。🙇‍♂️

手順

導入/設定
・ RSpecの導入
・ FactoryBotの導入
下準備
・ テストコード記述ファイルの作成
FactoryBot
・ ファクトリーボットファイル記述
Spec
・ テストコード記述

実装

導入/設定

ポイントは:development,:testのところに書くこと

Gemfile
group :development, :test do
 gem 'factory_bot_rails'
 gem 'rspec-rails', '~> 4.0.0'
end

の後にbundle installを忘れない

次に、RSpecのインストール

ターミナル
% rails g rspec:install

ここでインストールができないなどのエラーが出る場合はこの記事を参照
https://qiita.com/tech_hack_Rich/items/c8e12f5d9d3e9d677ed7

次に、テスト結果をターミナルで可視化するための設定をする

.rspec
--require spec_helper
--format documentation    ---追記する

これで導入と設定は完了

下準備

テストコードファイルの作成

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

これでテストコードを書くためのファイルを作成する、
同時にfactorybotのファイルもここで生成される

下準備OK

FactoryBot

こんな感じで記述

spec/factories/users.rb
FactoryBot.define do
  factory :user do
    nickname              {'test'}
    email                 {'test@example'}
    password              {'000000'}
    password_confirmation {password}
  end
end

Spec

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
    it 'emailが空では登録できない' do
      @user.email = ''
      @user.valid?
      expect(@user.errors.full_messages).to include "Email can't be blank"
    end
  end
end

完成🎉

0
0
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
0