title: How do I create a factory for models that have a has_one/belongs_to relationship with validations that are usually overcome by nested attributes?
body: <p>I have an Account model that has_one User model, and a User model that belongs_to Account model. I think that the basic code required for demonstration is:</p>
  
  <pre><code>class Account &lt; ActiveRecord::Base
    has_one :user
    validates_presence_of :user
    accepts_nested_attributes_for :user
  end
  
  class User &lt; ActiveRecord::Base
    belongs_to :account
    # validates_presence_of :account # this is not actually present,
                                     # but is implied by a not null requirement
                                     # in the database, so it only takes effect on
                                     # save or update, instead of on #valid?
  end
  </code></pre>
  
  <p>When I define associations in each factory:</p>
  
  <pre><code>Factory.define :user do |f|
    f.association :account
  end
  
  Factory.define :account do |f|
    f.association :user
  end
  </code></pre>
  
  <p>I get a stack overflow, as each is creating an account/user recursively.</p>
  
  <p>The way I've been able to solve this is to emulate nested attribute forms in my tests:</p>
  
  <pre><code>before :each do
    account_attributes = Factory.attributes_for :account
    account_attributes[:user_attributes] = Factory.attributes_for :user
    @account = Account.new(account_attributes)
  end
  </code></pre>
  
  <p>However, I'd like to keep this logic in the factory, as it can get out of hand once I start adding other modules:</p>
  
  <pre><code>before :each do
    account_attributes = Factory.attributes_for :account
    account_attributes[:user_attributes] = Factory.attributes_for :user
    account_attributes[:user_attributes][:profile_attributes] = Factory.attributes_for :profile
    account_attributes[:payment_profile_attributes] = Factory.attributes_for :payment_profile
    account_attributes[:subscription_attributes] = Factory.attributes_for :subscription
    @account = Account.new(account_attributes)
  end
  </code></pre>
  
  <p>Please help!</p>