6
1

More than 3 years have passed since last update.

FactoryBotで外部キーを使用する場合のやり方 〜別解

Posted at

はじめに

 先日、外部キーの値をFactoryBotで使い場合の投稿をしました。その後も調べていると、別の方法もあったので、紹介します。なんなら、こっちの方が簡単です。
FactoryBot、外部キーバリデーションで弾かれたときの解決方法

前回の方法

FactoryBot.define do
  factory :user do
    Faker::Config.locale = :ja
    room { FactoryBot.create(:room) } #ポイントはここ
    email { Faker::Internet.free_email }
    nickname { Faker::Name.last_name }
    password = Faker::Internet.password(min_length: 6)
    password { password }
    password_confirmation { password }
  end
end

アソシエーションを使った方法

FactoryBot.define do
  factory :user do
    Faker::Config.locale = :ja
    #roomのFakerを削除
    email { Faker::Internet.free_email }
    nickname { Faker::Name.last_name }
    password = Faker::Internet.password(min_length: 6)
    password { password }
    password_confirmation { password }

    association :room #←追記

  end
end

モデルにアソシエーションを記述するときのように
association :外部キーのモデル名
とするだけです。

まとめ

外部キーをFactoryBotを使用する場合は、素直にassociation :外部キーのモデル名とすると、勝手に外部キーと紐付けてテスト用の情報を生成してくれます。

6
1
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
6
1