has_many while respecting build strategy

2 views
Skip to first unread message

fowlduck

unread,
Oct 1, 2009, 5:04:21 PM10/1/09
to factory_girl
How do you build has_many relationships while respecting build
strategy?

CODE
=====================================================

class User
has_many :items
end

class Items
belongs_to :user
validates_presence_of :user_id
end

Factory.define(:user) do |u|
u.name "foo"
end

Factory.define(:user_with_items, :parent => :user) do |u|
u.items {|items| [items.association(:item), items.association
(:item)]}
end

Factory.define(:item) do |i|
i.color "red"
end

Factory.define(:item_with_user, :parent => :user) do |i|
i.association(:user)
end

=====================================================

If you run `@user = Factory(:user)` then `@user.items` contains the
two items. The issue is that the items aren't associated with the user
in the database. If you reload the association `@user.items(true)`
then you get back an empty array.

Also, I saw someone else pose this question recently and the only
reply was that someone had posted a solution to this on this mailing
list. I could not locate the solution. I know you can build them
manually or create helper methods on your own to build the object
graph, but I'd like to avoid that.

So, my question is how can you build up a has_many relationship in
factory_girl while respecting the build strategy?

Thanks for you time.

fowlduck

unread,
Oct 1, 2009, 7:12:14 PM10/1/09
to factory_girl
I ended up answering my own question. You can find the answer on
StackOverflow here:

http://stackoverflow.com/questions/1506556/hasmany-while-respecting-build-strategy-in-factorygirl

Basically it required that I patch factory girl. I'll get some tests
written for it and submit it soon, probably.
> If you run `@user = Factory(:user)` then `...@user.items` contains the
> two items. The issue is that the items aren't associated with the user
> in the database. If you reload the association `...@user.items(true)`
Reply all
Reply to author
Forward
0 new messages