Reputation: 1062
Here's the situation.
Gems: rails 3.2, factory_girl 2.5.1
class House
has_one :address, :as => :addressable
validates :address, :presence => true
accepts_nested_attributes_for :address
end
class Address
attr_accessor :nested
belongs_to :addressable, :polymorhic => true
validates :addressable, :presence => true, :unless => :nested
end
How this works.
<%= form_for @house do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.fields_for :address do |a| %>
<%= a.hidden_field :nested %>
<%= a.label :street_address %>
<%= a.text_field :street_address %>
What is the correct way to define a factory?
# does not work
Factory.define :house do |h|
h.association :address
end
# does not work
Factory.define :house do |h|
h.after_build do |record|
Factory.build(:address, :addressable => record, :nested => '')
end
end
# does not work
Factory.define :house do |h|
h.after_build do |record|
Factory.create(:address, :addressable => record, :nested => '')
end
end
So basically, the 'trick' that allows accepts_nested_attributes_for :address to get around the validations and create both records at the same time is not working in factory_girl. Currently, this ugly mess is the only solution.
home = House.new
home.name = 'On the prairie'
home.address_attributes = Factory.attributes_for(:address, :nested => '')
home.save
UPDATE Solution:
Factory.define :house do |h|
h.after_build do |record|
record.address = Factory.build(:address, :addressable => record)
end
end
Upvotes: 3
Views: 956
Reputation: 15772
Your second FactoryGirl attempt is close, but you need to do something with that built address.
FactoryGirl.define do
factory :house do
after_build do |house|
house.address = Factory.build(:address)
end
end
end
Upvotes: 3