在黄瓜中与factory_girl建立联系的最佳做法是什么?

时间:2009-11-04 12:38:08

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

我通常使用此步骤使用factory_girl设置记录:

Given /^the following (.+) records?:$/ do |factory, table|
  table.hashes.each do |hash|
    Factory(factory, hash)
  end
end

这是我在设置关联时的解决方法:

Given the following group record:
  | id | name |
  | 1  | foo  |
And the following item records:
  | name | group_id |
  | bar  | 1        |
  | baz  | 1        |
  # ...

我知道这很糟糕。使用ID会使域名人员的优势变得脆弱和神秘。

所以,我的问题是 - 建立与factory_girl的关联以及如上所述的表参数的最佳做法是什么?

3 个答案:

答案 0 :(得分:3)

您可以在工厂中定义多个关联 如下所示:

Factory.define :item do |item|
    item.name          "item_name"
end

Factory.define :group do |group|
    group.name          "group_name"
    group.items         { |items| [ items.association(:item), items.association(:item) ] }
end

执行Factory(:group)会创建包含两个项目的群组内容。

答案 1 :(得分:0)

回答我自己的问题:Pickle

答案 2 :(得分:0)

您可以使用已定义的FactoryGirl Cucumber步骤:
https://github.com/thoughtbot/factory_girl/blob/master/lib/factory_girl/step_definitions.rb

您可以在一个黄瓜步骤中设置您的项目和您的组:

Given the following items exists:
  | Name     | Group        |
  | Foo      | Name: Bar    |
  | Foam     | Name: Bar    |
  | Food     | Name: Bar    |

当这样做时,组'Bar'的创建使用'find_or_create_by'功能,因此第一个调用创建组,接下来的2个调用查找已创建的组。

通过这种方式,所有3个项目都具有相同的组“条形图”,您可以根据需要创建任意数量的分组项目。