James
James

Reputation: 5403

factory_girl_rails has_many association includes only one from a collection of many

I'm using factory_girl_rails instead of fixtures. Here are my models:

class User < ActiveRecord::Base
  has_many :tasks
end

class Task < ActiveRecord::Base
  belongs_to :user
end

Here are my factories:

Factory.define :user do |u|
end

Factory.define :task do |t|
  t.association :user, :factory => :user
end

In a test I do this:

user = Factory.create :user
(1..5).each { Factory.create(:task, :user => user)}

The problem that I'm experiencing is that afterward user.tasks contains only one task.

I have tried defining the user factory like this:

Factory.define :user do |u|
  u.tasks {|tasks|  [tasks.association(:user)] }
end

and like this:

Factory.define :user do |u|
  u.tasks {|tasks|  [tasks.association(:user), tasks.association(:user)] }
end

In both cases Factory.create(:user) causes an infinite loop.

Upvotes: 2

Views: 1252

Answers (2)

James
James

Reputation: 5403

Ah, this works:

Factory.define :task do |t|
  t.association :user
  t.after_create {|t| t.user.tasks << t}
end

John, your approach would work but I actually couldn't use what you described because in my test the tasks need to also reference another (unmentioned) model and I don't see a way of referencing it in the user_with_tasks factory definition.

Upvotes: 0

John Hinnegan
John Hinnegan

Reputation: 5962

I think what you're doing is backwards -- you can create Tasks from the User, but not visa versa like you're trying to do. Conceptually, the association goes from the user to the task.

What I did was create a special factory for that type of user.

Factory.define :user_with_tasks, :parent => :user do |user|
  user.after_create {|u| 5.times { Factory.create(:task, :user => user) } }
end 

Also, if you just want to use the default factory, you just do this

Factory.define :task do |f|
  f.user :user
end 

No need to specify the factory

UPDATE: Looks like others have done something similar in the past: Populating an association with children in factory_girl

Upvotes: 3

Related Questions