title: Dependent factories in Factory Girl
body: <p>I have 2 factories. Beta_user and Beta_invite. Basically before a Beta_user can validly save I have to create an entry of Beta_invite. Unfortunately these models don't have clean associations, but they do share an email field. </p>
  
  <pre><code>Factory.sequence :email do |n|
    "email#{n}@factory.com"
  end
  
  #BetaInvite
  Factory.define :beta_invite do |f|
    f.email {Factory.next(:email)}
    f.approved false
    f.source "web"
  end
  
  #User
  Factory.define :user do |f|
    f.email {Factory.next(:email)}
    f.password "password"
  end
  
  
  #User =&gt; BetaUser
  Factory.define :beta_user, :parent =&gt; :user do |f|
    f.after_build do |user|
      if BetaInvite.find_by_email(user.email).nil?
        Factory(:beta_invite, :email =&gt; user.email)
      end
    end
  end
  </code></pre>
  
  <p>So in the beta beta_user factory I am trying to use the after_build call back to create the beta_invite factory.</p>
  
  <p>However it seems to be acting async or something. Possibly doing the find_by_email fetch?</p>
  
  <p>If I try this:</p>
  
  <pre><code>Factory(:beta_user)
  Factory(:beta_user)
  Factory(:beta_user)
  </code></pre>
  
  <p>I get a failure stating that there is no record of a beta_invite with that users email.</p>
  
  <p>If instead I try:</p>
  
  <pre><code>Factory.build(:beta_user).save
  Factory.build(:beta_user).save
  Factory.build(:beta_user).save
  </code></pre>
  
  <p>I get better results. As if calling the .build method and waiting to save allows time for the beta_invite factory to be created. Instead of calling Factory.create directly. The docs say that in the case of calling Factory.create both the after_build and after_create callbacks get called. </p>
  
  <p>Any help is much appreciated.</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>So the User model I am using does a <code>before_validation</code> call to the method that checks if there is a beta invite. If I move this method call to <code>before_save</code> instead. It works correctly. Is there something i'm over looking. When does factory_girl run the <code>after_build</code> and <code>after_create</code> callbacks in relation to active-record's <code>before_validation</code> and <code>before_save</code>?</p>