How can I define multiple associated objects using Factory Girl?
Asked Answered
S

3

8

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 Users, that have a bunch of Posts?

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.

Sg answered 26/6, 2009 at 6:41 Comment(0)
C
5

I'm not sure if this is the most correct way of doing it, but it works.

Factory.define(:user) do |u|
  u.login 'my_login'
  u.password 'test'
  u.password_confirmation 'test'
  u.roles {|user| [user.association(:admin_role),
                      user.association(:owner_role, :authorizable_type => 'User', :authorizable_id => u.id) ]}
end
Cedrickceevah answered 20/8, 2009 at 20:37 Comment(0)
S
1

A recent update to factory girl allows associations to be specified with callback blocks

Scattering answered 22/12, 2009 at 3:1 Comment(0)
G
1

I created an active_factory plugin, that deals with your situation in spec like this:

models { user - posts(3) }

If there is an interest, i may try to create integration with factory_girl factories.

Gasaway answered 20/4, 2011 at 20:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.