I have a very simple association set up in FactoryGirl, but it's not working for some reason. The app is for a tour company, so each Tour has a Destination (I'm using ActiveRecord, so the Tour
model belongs_to
a Destination
-- this association is required for all tours). So I set up my factories like this:
# spec/factories.rb
FactoryGirl.define do
factory :destination do
name "Example Destination"
city "Example City"
state "CA"
end
factory :tour do
departure_date { 1.day.from_now }
return_date { 1.day.from_now }
destination
end
end
However, when I call FactoryGirl.attributes_for(:tour)
, it returns:
{:departure_date => Mon, 04 Nov 2013 17:51:26 UTC +00:00,
:return_date => Mon, 04 Nov 2013 17:51:26 UTC +00:00}
No destination_id
! Why?
The destination
factory works just fine.
I tried defining the association the old way association :destination, factory: :destination
, but that didn't help. I can get it to work if I manually define the destination_id
as destination_id FactoryGirl.create(:destination).id
, but I shouldn't have to do that. Any idea why it's not working?
attributes_for
doesn't doesn't load associated objects. It only generates attributes for the object that you're requesting.
To get it to load the associated destination
, use build
or create
instead.
The attributes_for doesn't create the associations attributes (by design I believe). This should work:
FactoryGirl.attributes_for(:tour, :destination_attributes => FactoryGirl.attributes_for(:destination))
But, this might be a slicker solution:
https://stackoverflow.com/a/10294322/632735
:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.