auralbee
auralbee

Reputation: 8841

FactoryGirl and Associations

I have two classes and two factories:

class User
 belongs_to :company
end

class Company
 has_many :users
end

Factory.define :user do |u|
 u.name "Max"
 u.association :company
end

Factory.define :user2, :parent => :user do |u|
 u.name "Peter"
end

Factory.define :company do |c|
 c.name "Acme Corporation"
end

How can I achieve having both users in the same company? When running the tests, FactoryGirl creates two company records but I want both users to be connected to one record.

Any hints?

Upvotes: 1

Views: 349

Answers (2)

apneadiving
apneadiving

Reputation: 115541

Try this:

user1 = Factory(:user)
user2 = Factory(:user2, :company => user1.company) 

Upvotes: 3

Serabe
Serabe

Reputation: 3924

@company = Factory.create :company
@first_user = Factory.create :user, :company => @company
@second_user = Factory.create :user, :company => @company

Something like that should do, but please, read my comment first, I think you got the wrong idea about Factory Girl.

Upvotes: 5

Related Questions