Factory Girl and has_many / has_many :through associations
If you want to create has_many and has_many through associations in factory_girl as I once did, you will need to put it inside square brackets:
Factory.define :user do |user|
user.name "My Name"
user.groups {|groups| [groups.association(:group)]}
end
This will ensure that user.groups is not overriden by a single Group object, but by an array with a Group inside.
Categories: programming, rails

If it wasn’t for excellent people like you – who find an answer to an annoying problem like this and then publish it to the world – people like me would spend hours hitting our heads against a brick wall. I salute you!
Just started using Factory Girl and it looks really useful but, unless I’m being thick, I couldn’t find this in the rdoc.
I try your suggestion but…
All groups end up with “user_id = nil”
Using factory_girl 1.2.0
can you tell us how your relationships are defined in the models so we can help you better?
I’m sure you couldn’t, and that’s not your fault. It’s not there. I found it on a blog, but since I posted a few days after reading it, I could not remember the source, for what I am sorry.
I simply tried the suggestion making
class User
has_many :posts
class Post
belongs_to :user
In the code above all groups end up with “user_id = nil”. Actually the factory creates the posts and the users. And the result is many unrelated posts and users.
Can we consider it a bug or missing feature of factory girl?
The one to many definition does not work:
user.groups {|groups| [groups.association(:group)]}
Umur,
I was able to associate the child objects properly by ensuring they were written to the database when defining the lazy attribute, like so:
user.groups {|groups| [Factory.create(:group)] }
(.create writes the group to the database and ensures it has an ID, which the association then picks up on.)
I had a huge problem creating these associations correctly w/ factory_girl, I finally got it fixed with help, you can check it out here: http://railsondave.blogspot.com/2009/05/creating-hasmany-through-factories-with.html