0
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 1 year has passed since last update.

FactoryBotメモ

Last updated at Posted at 2022-06-21

FactoryBotとは

テスト用のダミーデータを簡単に作成できるGem。

導入

group :development, :test do
 # 省略
 gem 'factory_bot_rails'
end
% bundle install

FactoryBotの設定

RSpec.configure do |config|
 # 省略
 config.include FactoryBot::Syntax::Methods
end

system/spec_helper.rbに上記を記載することで、Factroy作成時にFactoryBotの記載を省略できる。

factoriesの作成

% rails g factory_bot:model user

factroriesディレクトリ直下にusers.rbが作成される。

サンプルデータの記載

雛形

FactoryBot.define do
 factory :user do
  
 end
end

基本的な書き方

FactoryBot.define do
 factory :user do
  name { 'yamada' }
  password { 'password' }
  password_confirmation { 'password' }
 end
end

name password password_confirmation はUserモデルのカラム。

一意のサンプルデータの作成

FactoryBot.define do
 factory :user do
  sequence(:email) { |n| "test#{n}@example.com" }
  sequence(:name) { |n| "test#{n}" }
 end
end

traitの利用

例えば、管理ユーザーや一般ユーザーなど複数のサンプルデータを作成したい時、traitを使うと一つのファイルに記載ができる。

FactoryBot.define do
 factory :user do
  trait :admin do
   name { 'admin_user' }
   role { :admin }
  end
  trait :general do
   name { 'general_user' }
   role { :general }
  end
 end
end

テストデータの作成

let(:user) { create :user }
# traitの利用
let(:admin) { create :user, :admin }
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?