FactoryGirl和协会

时间:2011-08-16 09:51:21

标签: ruby-on-rails ruby factory-bot

我有两个班级和两个工厂:

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

如何让两个用户都在同一家公司?运行测试时,FactoryGirl会创建两个公司记录,但我希望两个用户都连接到一个记录。

任何提示?

2 个答案:

答案 0 :(得分:5)

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

这样的事情应该做,但请先阅读我的评论,我认为你对Factory Girl有错误的想法。

答案 1 :(得分:3)

试试这个:

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