Read more

FactoryBot: Passing attributes to associated records using transient attributes

Thomas Klemm
May 08, 2015Software engineer
FactoryBot.define do

  factory :parent do
    transient do
      child_name nil
      child_allowed_to_drive false
    end
    
    child do
      association(:child, name: child_name, allowed_to_drive: child_allowed_to_drive)
    end
  end

  factory :child do
    name 'Child'
    allowed_to_drive false
  end

end

# Usage
daughter = FactoryBot.create(:parent, child_name: 'Lisa').child
daughter.name # => 'Lisa'
daughter.allowed_to_drive? # => false

son = FactoryBot.create(:parent, child_name: 'Benedikt', child_allowed_to_drive: true).child
son.name # => 'Benedikt'
son.allowed_to_drive? # => true
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot
Posted by Thomas Klemm to makandra dev (2015-05-08 13:48)