title: Testing Rails Deep Nested Attributes with RSPEC and FactoryGirl
body: <p>I need some help getting my factory_girl settings correct on this has one through many with nested attributes. Here's the three models for reference. </p>
  
  <p>location.rb</p>
  
  <pre><code>class Location &lt; ActiveRecord::Base
    has_many :person_locations
    has_many :people, through: :person_locations
  end
  </code></pre>
  
  <p>person_location.rb</p>
  
  <pre><code>class PersonLocation &lt; ActiveRecord::Base
    belongs_to :person
    belongs_to :location
    accepts_nested_attributes_for :location, reject_if: :all_blank
  end
  </code></pre>
  
  <p>person.rb</p>
  
  <pre><code>class Person &lt; ActiveRecord::Base
    has_many :person_locations
    has_many :locations, through: :person_locations
    accepts_nested_attributes_for :person_locations, reject_if: :all_blank
  end
  </code></pre>
  
  <p>Notice that locations is nested under the person record, but it needs to go through two models to be nested. I can get the tests working like this: </p>
  
  <pre><code>it "creates the objects and can be called via rails syntax" do 
     Location.all.count.should == 0
     @person = FactoryGirl.create(:person)
     @location = FactoryGirl.create(:location)
     @person_location = FactoryGirl.create(:person_location, person: @person, location: @location)
     @person.locations.count.should == 1
     @location.people.count.should == 1
     Location.all.count.should == 1
  end
  </code></pre>
  
  <p>I should be able to create all three of these records within one line but haven't figured out how to yet. Here's the structure I would like to have work correctly :</p>
  
  <pre><code>factory :person do 
    ...
    trait :location_1 do 
      person_locations_attributes { location_attributes { FactoryGirl.attributes_for(:location, :location_1) } }
    end
  end
  </code></pre>
  
  <p>I have other models which are able to create via a similar syntax, but it has only one nested attribute versus this deeper nesting. </p>
  
  <p>As entered above, I get the following error: </p>
  
  <pre><code>FactoryGirl.create(:person, :location_1)
  
     undefined method `location_attributes' for #&lt;FactoryGirl::SyntaxRunner:0x007fd65102a380&gt;
  </code></pre>
  
  <p>Furthermore, I want to be able to test properly my controller setup for creating a new user with nested location. It will be tough to do this if I can't get the call down to one line.</p>
  
  <p>Thanks for your help!! Hopefully I provided enough above to help others as well when they are creating a has many through relationship with nested attributes. </p>