title: How should I set up complex Factories in Rails?
body: <p>In my rails application I have three objects I would like to model for a particular Rspec test. These are Organizations, Users, and Sales Opportunities.</p>
  
  <pre><code>class Organization
    has_many :users
  end
  
  class User
    has_many :sales_opportunities
  end
  </code></pre>
  
  <p>An Organization has to have a unique name, and for the authorisation/authentication aspects of my app to work, both users need to belong to the same Organization. For the purposes of this test I want one User to be admin and one to be non-admin.</p>
  
  <p>This works successfully in other parts of my application (e.g. sign up - the first user is automatically the admin, subsequent users are not, and for viewing links etc on pages). However what I now need to do is create two users (both belong_to one organization), make one of them the admin, and then when I delete the <strike>sales_opportunity</strike> non-admin user any sales_opportunities that belonged to this non-admin user should transfer ownership to the admin (for re-allocation).</p>
  
  <p>FWIW I am using associations for some of the other tests - but in this case I can't create two users associated with one organization, so I've used:</p>
  
  <pre><code>before(:create) do |organization|
      organization.users &lt;&lt; FactoryGirl.build(:user ...admin params)
      organization.users &lt;&lt; FactoryGirl.build(:user ...non_admin params)
  end
  </code></pre>
  
  <p>in the factory for the organization to build 2 users who both belong to one organization and have different characteristics. This works well.</p>
  
  <p>If I try to add another before(:create) to the factory to then build a sales_opportunity it fails (because the users aren't created yet I believe). After(:create) statements also fall flat. I've also tried defining the non_admin user in the tests themselves (e.g. by using a let(:non_admin) = Organization.users.last and then non_admin.sales_opportunities.create statement), but this fails to product any sales opportunities (not sure what it does).</p>
  
  <p>Are there any good resources on how to build tests like this? I can write the code to solve the problems in no time - I seem to waste a huge amount of time writing the tests first. I'm sure these are not particularly DRY either looking through my factories.</p>
  
  <p>Any help would be appreciated.</p>