4
0

More than 1 year has passed since last update.

結論

require 'factory_bot_rails'をseedファイルの上部に記載することでFactoryBotが使えます。

seedファイル
# rquireが重要!!!わすれないで!!
require 'factory_bot_rails'

# 例1:1個データを作る
FactoryBot.create(:parent, name: '親1')
# 例2:いっぱいデータ作る
FactoryBot.create_list(:child, 5, name: '子')
# 例3:戻り値を使って作ったデータを取得する & データをセットする
parent = FactoryBot.create(:parent, name: '親1')
FactoryBot.create_list(:child, 5, name: '子', parent: parent)

事前準備

Gem

Gemのfactory_bot_railsが必要です。Gemfileに追記しましょう。

Factory

上記例の場合、このような感じのFactoryが必要です。

factoryファイル
# Parent側
FactoryBot.define do
  factory :parent do
    sequence(:name) { |n| "親#{n}" }
    sequence(:age) { rand(15..100) }
  end
end

# Child側
FactoryBot.define do
  factory :child do
    association :parent

    sequence(:parent_id) { parent.id }
    sequence(:name) { |n| "子#{n}" }
    sequence(:age) { rand(0..20) }
  end
end

何が嬉しいのか

  • データ作成をすべてFactory側に集約できる
  • create_listを使って一気にデータを作れる

参考

FactoryGirlの記事はあったが、FactoryBotの記事が無かったので。ご参考になれば幸いです。

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