FactoryGirl.define做 工厂:contacts_team做 结束结束
FactoryGirl.define做 工厂:团队做 名称 ” 安全 </跨度> 检查 </跨度> 球队” 结束结束
FactoryGirl.define做 工厂:关系做 结束结束
FactoryGirl.define做 工厂:位置做 名称 ” 安全 </跨度> 地点” 结束结束
如果使用factory_girl很难/不可能这样做:我怎么能用直接的rspec做到这一点?
我上周才有类似的要求。
在工厂结束时,您可以致电下一家工厂,然后他们就会相关联。例如:
/spec/factories/contacts.rb
FactoryGirl.define do factory :contact do |c| first_name "Homer" last_name "Simpson" title "Nuclear Saftey Inspector" # now, call the other two factories relationship contacts_team end factory :contacts_team do # call the team factory team end factory :relationship do # call the location factory location end # define the team and location factories... end
现在,在/spec/controllers/contacts_controller_spec.rb中
contact = FactoryGirl.create(:contact)
您可以使用工厂女孩来创建联系人,即使您只需要一个位置,因为所有内容都会立即生成。
的 替代(rspec) 强>
不要“链接”你的工厂,而是在/spec/controllers/contacts_controller_spec.rb中
contact = FactoryGirl.create(:contact) # use .create_list(model, number, parent) to make children of a specific parent contacts_team = FactoryGirl.create_list(:contacts_team, 3, :contact => contact) relationship = FactoryGirl.create_list(:relationship, 3, :contact => contact) team = FactoryGirl.create_list(:team, 3, :contacts_team => contacts_team) location = FactoryGirl.create_list(:location, 3, :relationship => relationship)
这将创建一个联系人,其中包含3个contact_teams(包含3个团队),以及3个关系(包含3个位置)
希望这可以帮助您找出正确的模式来制作您的测试数据:)
这是答案。我们需要建立相关的记录( contacts_team 记录和 relationship 记录)然后我们将所有记录完全保存到数据库中(就像rails如何保存嵌套属性一样):
contacts_team
relationship
#factories/contact.rb FactoryGirl.define do factory :contact do first_name "Homer" last_name "Simpson" title "Nuclear Saftey Inspector" agency contacts_teams {build_list :contacts_team, 1 } relationships {build_list :relationship, 1 } end end #factories/contacts_teams.rb FactoryGirl.define do factory :contacts_team do team end end #factories/teams.rb FactoryGirl.define do factory :team do name "Safety Inspection Team" end end #factories/relationships.rb FactoryGirl.define do factory :relationship do location end end #factories/locations.rb FactoryGirl.define do factory :location do name "Safety Location" end end
那么你需要做的就是:
create(:contact)
有了这一切,它立刻创造了一个 contact 记录,a team 记录,a location 记录,关联 contacts_team 记录,以及相关的 relationship 记录。
contact
team
location
基本上,你可以采取多种方式。但通常建议的一种方法是使用FactoryGirl after(:create) 要么 after(:build) 。在您的情况下,如果您的所有型号都有工厂,您可以轻松致电:
after(:create)
after(:build)
after(:create) do |team, evaluator| create_list(:contact_team, 5, team: team) end 根据文档,在(:create)之后产生团队和评估者,它们存储工厂的所有值,包括瞬态属性
after(:create) do |team, evaluator| create_list(:contact_team, 5, team: team) end
这将为您创建5个与团队关联的contact_teams。对于每个工厂,如果您定义这样的所有关系,您将定义完整的关联。另一种方法是遵循诺姆的建议,这也是好的,但有其自身的局限性。 您可以在这里找到更多信息: FactoryGirl协会