I kind of have a chicken and egg type problem. I have an Isp model that has a default_domain _id, that I need to populate for my tests. The problem is Domain belongs to the ISP. So I am trying to figure out how to build the factory to generate an ISP
factories/isp.rb
FactoryGirl.define do
factory :isp do
sequence :name do |n|
"ISP" + n.to_s
end
end
end
factories/domain.rb
FactoryGirl.define do
factory :domain do
isp
account
sequence :dn do |n|
"foo-#{n}.com"
end
active :true
end
end
app/models/isp.rb
class Isp < ActiveRecord::Base
has_many :domains
belongs_to :default_domain, class_name: 'Domain'
end
app/models/domain.rb
class Domain < ActiveRecord::Base
belongs_to :isp
...
end
I’ve tried using after(:create) callbacks in the factory, that just seems to create circular reference. Tried using a block to lazily evaluate it. Same thing. Just at a loss where to look next or what I should try..
It appears you found a solution. However, if you want to utilize factories to create the default_domain attribute, try this.
First, If you change your
domainfactory so that it does not reference theispfactory, you’ll avoid the circular reference.Second, in your
ispfactory definition, you can do this:This will let you utilize FactoryGirl for the more complicated attributes of the
Domainmodel, and if you wanted to customize thednfield from outside the factory, you could use transient attributes and utilize them in theafter_createhook.