How do I define associated Factories with FactoryBot?
factory-bot, rspec, ruby, ruby-on-rails-3
Solution
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
Problem
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?