LoginSignup
0
0

More than 3 years have passed since last update.

[memo]テストコード準備と実行

Last updated at Posted at 2021-02-21

テストコードの準備

# Gemを追加 Gemfile
# group :development, :testというグループの中に記述
% gem 'rspec-rails', '~> 4.0.0'

# ターミナル
% bundle install

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

# .rspecに設定を追加
--require spec_helper
--format documentation

テストコードを記述するファイルを用意

# ターミナル
# Userモデルのテストファイルを生成
% rails g rspec:model user

テストコードの実行

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

FactoryBotのGem導入

# Gemfile
# group :development, :test do へ記述
gem 'factory_bot_rails'

# ターミナル
% bundle install

インスタンスの生成を切り出すファイルを作成

FactoryBotの記述を格納するディレクトリfactoriesと、
Userモデルに対するFactoryBotのファイル
users.rbを、以下のように手動で作成

spec > factories > users.rb

※この操作は、テストコードを記述するファイルを生成した後からFactoryBotを導入するときに必要です。
FactoryBot導入後はテストコードを記述するファイルを生成すると同時に、自動生成されます。

FactoryBotの記述を編集

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

FactoryBotを使う記述

spec/models/user_spec.rb
require 'rails_helper'

RSpec.describe User, type: :model do
  before do
    @user = FactoryBot.build(:user)
    #処理速度を落とす記述
    sleep 0.1
  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

ランダムな値の生成ができるFakerを導入

# Gemfile
# group :development, :test do へ記述
gem 'faker'

# ターミナル
% bundle install

FactoryBotの記述をFakerを使ったものへ編集

spec/factories/users.rb
FactoryBot.define do
  factory :user do
    nickname              { Faker::Name.initials(number: 6) }
    email                 { Faker::Internet.free_email }
    password              { '000000' }
    password_confirmation { password }
  end
end

▼Fakerのリストは公式Github
https://github.com/faker-ruby/faker

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