2

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?

4

2 回答 2

4

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.

于 2013-11-03T18:23:35.163 回答
1

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

:)

于 2013-11-03T18:23:45.820 回答