Problem creating associations which share attributes with factory

6 views
Skip to first unread message

James Adam

unread,
Oct 3, 2009, 9:21:16 PM10/3/09
to factory_girl
Hi all,

I'm having a little problem defining factories where associated models
need to refer to the same instances as other associations within the
same factory. Let me illustrate with a very simplified example:

Factory.define(:user) do |user|
end

Factory.define(:review) do |review|
review.association :user
end

Factory.define(:activity) do |activity|
activity.association :user #
this user
activity.association :review, :user => activity.user # should be
the same as this user
end

Basically, we have a Review, written by a User, and then an Activity
record which belongs to a User and a Review, and the User should be
the same user as belongs to the Review.

However, I cannot figure out how to get a hold of the same user
instance. I've tried any number of ways:

activity.association :review, :user => activity.user
activity.review { |a| a.association :review, :user => a.user }
activity.review { |a| a.association :review, :user =>
activity.user }

... none of these work. Does anyone have any ideas? Is this even
possible with FactoryGirl?

Thanks,

James

Mark Wilden

unread,
Oct 4, 2009, 8:33:01 PM10/4/09
to factor...@googlegroups.com
On Sat, Oct 3, 2009 at 6:21 PM, James Adam <ja...@lazyatom.com> wrote:
>
>  Factory.define(:user) do |user|
>  end
>
>  Factory.define(:review) do |review|
>    review.association :user
>  end
>
>  Factory.define(:activity) do |activity|
>    activity.association :user                                       #
> this user
>    activity.association :review, :user => activity.user   # should be
> the same as this user
>  end
>
> Basically, we have a Review, written by a User, and then an Activity
> record which belongs to a User and a Review, and the User should be
> the same user as belongs to the Review.

You could just do it "manually":

user = Factory(:user)
review = Factory(:review, :user => user)
activity = Factory(:activity, :user => user, :review => review)

///ark

goodwill

unread,
Oct 17, 2009, 3:33:47 AM10/17/09
to factory_girl
This work of course... but it would mean certain really default stub
records has to be remembered to be created everytime! I saw a few fork
on github adding find_or_create, which I think is a good direction.
Any chance its integrated back to the core?
Reply all
Reply to author
Forward
0 new messages