The Factory Girl docs offer this syntax for creating (I guess) parent-child associations...
Factory.define :post do |p|
p.author {|a| a.association(:user) }
end
A post belongs to a User (its "author").
What if you want to define a Factory to create User
s, that have a bunch of Post
s?
Or what if it's a many-to-many situation (see update below for example)?
UPDATE
I thought I had figured it out. I tried this...
Factory.define(:user) do |f|
f.username { Factory.next(:username) }
# ...
f.roles { |user|
[
Factory(:role),
Factory(:role, {:name => 'EDIT_STAFF_DATA'})
]
}
end
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.
So I return to my original question. If you have a many-to-many relationship, like say Users
and Roles
, how can you define a Factory that will return Users
with some associated Roles
? Note that Roles
must be unique, so I can't have F.G. creating a new "ADMIN" Role
in the DB every time it creates a User
.