开发者

FactoryGirl and Associations

开发者 https://www.devze.com 2023-03-28 14:58 出处:网络
I have two classes and two factories: class User belongs_to :company end class Company has_many :users end

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 us开发者_开发百科ers to be connected to one record.

Any hints?


@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.


Try this:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号