title: How can I define multiple associated objects using Factory Girl?
body: <p>The Factory Girl docs offer this syntax for creating (I guess) parent-child associations...</p>
  
  <pre><code>  Factory.define :post do |p|
      p.author {|a| a.association(:user) }
    end
  </code></pre>
  
  <p>A post belongs to a User (its "author").</p>
  
  <p>What if you want to define a Factory to create <code>User</code>s, that have a bunch of <code>Post</code>s?</p>
  
  <p>Or what if it's a many-to-many situation (see update below for example)?</p>
  
  <hr>
  
  <p>UPDATE</p>
  
  <p>I thought I had figured it out. I tried this...</p>
  
  <pre><code>Factory.define(:user) do |f|
    f.username { Factory.next(:username) }
  
    # ...
  
    f.roles { |user|
      [
        Factory(:role),
        Factory(:role, {:name =&gt; 'EDIT_STAFF_DATA'})
      ]
    }
  end
  </code></pre>
  
  <p>It seemed to work at first, but then I got validation errors because F.G. was trying to save the user twice with same username and email.</p>
  
  <p>So I return to my original question. If you have a many-to-many relationship, like say <code>Users</code> and <code>Roles</code>, how can you define a Factory that will return <code>Users</code> with some associated <code>Roles</code>? Note that <code>Roles</code> must be unique, so I can't have F.G. creating a new "ADMIN" <code>Role</code> in the DB every time it creates a <code>User</code>.</p>