はじめに
オリジナルアプリ制作にあたり、FactoryBotとFakerを用いてテストを行ったので、忘れないように載せておこうと思います。
FactoryBot: あらかじめ各クラスのインスタンスに定める値を設定しておくGem
Faker: メールアドレス、人名、パスワードなど、ランダムな値を生成するGem
前提として、テストファイルuser_spec.rbがすでに生成してあるとする。
1.gemの導入と段取り
- 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 で作成したファイル内にFactoryBotとFakerを用いてコードを記述する
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
最後に
一度学習した内容でしたが、うろ覚えだったので、復習できてよかったと思います!