Search code examples
ruby-on-railsrubyassociationsfactory-bot

Update associated object within a FactoryBot trait


Sample Factory

FactoryBot.define do
  factory :fruit do
    name { "Kiwi" }
    status { "available" }
    store { Store.first }
  end

  trait :unaccessible do
    status { "unaccessible" }
    store { status: "closed", hours_before_open: 2 }
  end
end

Inside the trait block, I've been struggling to find a way to update the properties of the associated Store object. Didn't find an example in the Traits section of the documentation. Also didn't find any example searching here in SO and Googling. Is this even possbile?


Solution

  • Use an after block to override those attributes.