1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

テストコードの効率化

1
Last updated at Posted at 2021-01-08

はじめに

オリジナルアプリ制作にあたり、FactoryBotとFakerを用いてテストを行ったので、忘れないように載せておこうと思います。
FactoryBot: あらかじめ各クラスのインスタンスに定める値を設定しておくGem
Faker: メールアドレス、人名、パスワードなど、ランダムな値を生成するGem
前提として、テストファイルuser_spec.rbがすでに生成してあるとする。

1.gemの導入と段取り

  1. FactoryBotとFakerのGemをGemfileのgroup :development, :test do内に記述し、bundle installする。
Gemfile
group :development, :test do
# 中略
  gem 'factory_bot_rails'
  gem 'faker'
end

2. specディレクトリ内にFactoryBot用のディレクトリ(①)を作成し、さらにその中にFactoryBot用のファイル(②)を作成する  (例) spec / factories(①) / users.rb(②)

2.FactoryBot用ファイル(②)内に記述

1 で作成したファイル内にFactoryBotFakerを用いてコードを記述する
Fakerの公式GitHub https://github.com/faker-ruby/faker

FactoryBot用ファイル(②)
FactoryBot.define do
  factory :user do
    name        {Faker::Name.name}
    email       {Faker::Internet.free_email}
    password    {Faker::Internet.password(min_length: 8)}
    birthday    { '2000-01-01' }
   # 中略
  end
end

3.テストコードの記述

FactoryBot.build(:user)と記述し、Userのインスタンスを生成する。
また、beforeを用いて、それぞれのテストコードを実行する前にインスタンスを生成。

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.name = ""
      @user.valid?
      expect(@user.errors.full_messages).to include "Name 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

最後に

一度学習した内容でしたが、うろ覚えだったので、復習できてよかったと思います!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?