title: How to establish associations using FactoryGirl to test a Rails app
body: <p>I'm just beginning to experiment with Rails tests. I'm having trouble getting started. </p>
  
  <p>My first tests require a User, which I'm creating within FactoryGirl. But my model validates presence of an invitation.</p>
  
  <pre><code>class User
    has_many :sent_invitations, :class_name =&gt; 'Invitation', :foreign_key =&gt; 'sender_id'
    belongs_to :invitation
    validates_presence_of :invitation_id
  end
  
  class Invitation
    belongs_to :sender, :class_name =&gt; 'User'
    has_one :recipient, :class_name =&gt; 'User'
  end
  </code></pre>
  
  <p>How do I generate an invited user using FactoryGirl?</p>
  
  <p>I've tried a few approaches, but the association is not being set. The one that seems most likely to work is something like:</p>
  
  <pre><code>factory :invitation do
    token "MyInvitationToken"
    recipient_email "test@example.com"
  
    factory :invited_user do
      association :user, :factory =&gt; :user
    end
  end
  
  factory :user do
    email "test@example.com"
  end
  </code></pre>
  
  <p>This is failing with <code>Validation failed: Invitation is required</code>. </p>
  
  <p>What is the correct way to establish this association with FactoryGirl?</p>
  
  <p>For bonus points, how can I modify this so the :invitation.recipient_email is a sequence <code>sequence(:recipient_email) { |n| "test#{n}@example.com" }</code>, and that this value gets passed to the invited_user's email column for each iteration.</p>