How do I define associated Factories with FactoryBot?
Asked Answered
I

1

10

Given two models, Alert and Zipcode, where one Alert must have 1 or more Zipcodes:

class Alert < ActiveRecord::Base
  attr_accessible :descr, :zipcode

  has_many :zipcode
  validates :zipcode, :length => { :minimum => 1 }
end

class Zipcode < ActiveRecord::Base
  attr_accessible :zip
  belongs_to :alert
end 

How do I write my FactoryBot factories so that:

  • Zipcode factories are defined in their own file
  • Alert factories are defined in their own file
  • Alert can rely on the factory defined by Zipcode?

All of the documentation and examples I read expect you to define the contained class inside the parent factory file, blob them all together, or make some other compromise or work-around. Isn't there a clean way to keep the spec factories separate?

Irisation answered 24/8, 2012 at 23:16 Comment(0)
I
12

The trick is to make sure the container class, that is, the one with a has_many statement in its definition, creates the contained class as an array in FactoryBot. For example:

In your spec/factories/zipcodes.rb:

FactoryBot.define do
  factory :zipcode do
    zip { 78701 + rand(99) } 
  end
end

And in spec/factories/alerts.rb:

FactoryBot.define do
  factory :alert do
    zipcode { Array.new(3) { FactoryBot.build(:zipcode) } }
  end
end
Irisation answered 24/8, 2012 at 23:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.