コード日進月歩

しんくうの技術的な小話、メモ、つれづれ、など

FactoryBotのtraitでリレーション先のModelのtraitを使って設定することができる

他のクラスのtraitって使えるんだネタ

環境

factory_bot (5.0.2)
  activesupport (>= 4.2.0)
factory_bot_rails (5.0.2)
  factory_bot (~> 5.0.2)
  railties (>= 4.2.0)

使い方

関連のあるモデルに

userとhas_manyの関係にあるmessagesがあるとする。そのときに以下のようなFactoryBotを作る

# == Schema Information
#
# Table name: users
#
#  id         :bigint(8)        not null, primary key
#  name       :string(255)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

FactoryBot.define do
  factory :user do
    name {"hoge"}

    trait "special_name" do
      name {"special"}
    end
  end
end
# == Schema Information
#
# Table name: messages
#
#  id         :bigint(8)        not null, primary key
#  name       :string(255)
#  user_id    :integer
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

FactoryBot.define do
  factory :message do
    name {"simple_letter"}

    trait "with_special_user" do
      association :user, :special_name
      name {"special message"}
    end
  end
end

このように定義すると、message側のtraitでにuserのtraitを使うことができる。使い方は以下。

demo_message = FactoryBot.create(:message, :with_special_user)
demo_message.user.name
# => "special"
demo_message.name
# => "special message"

参考元リンク