LoginSignup
0
0

More than 1 year has passed since last update.

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

Posted at

アウトプット

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インスタンス変数を用いてセットアップをすることで、さらに記述量を減らすことができる。

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