LoginSignup
0

posted at

FactoryBotを使用したインスタンス生成の共通化

アウトプット

FactoryBotとは、インスタンスをまとめることができるGem。

spec/factories/users.rb
FactoryBot.define do
  factory :user do
    email                 {'test@com'}
    password              {'abcdef1234'}
    password_confirmation {'abcdef1234'}
  end
end
# FactoryBotを使用しない場合
user = User.new(email: 'tset@com', password: 'abcdef1234', password_confirmation: 'abcdef1234')
# FactoryBotを使用する場合
user = FactoryBot.build(:user)
spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
  describe 'ユーザー新規登録' do
    it 'emailが空では登録できない' do
      user = FactoryBot.build(:user)
      user.email = ''
      user.valid?
      expect(user.errors.full_messages).to include "Email can't be blank"
    end
  end
end

学んだこと

インスタンス生成の記述を、FactoryBotを使うことで、短くまとめることができる。
今回は記述してないが、テストコードを書く前にbeforeインスタンス変数を用いてセットアップをすることで、さらに記述量を減らすことができる。

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
What you can do with signing up
0