5

我通常使用这个步骤来设置 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        |
  # ...

我知道这很糟糕。从域人员的角度来看,使用 ids 会使整个事情变得脆弱和神秘。

所以,我的问题是——建立与 factory_girl 的关联和上面的表参数的最佳做法是什么?

4

3 回答 3

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

执行 aFactory(:group)将创建包含两个项目的组 uplet。

于 2009-11-04T13:06:54.890 回答
0

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

您只需一个 Cucumber 步骤即可设置您的项目和组:

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

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

这样,所有 3 个项目将具有相同的组“栏”,您可以根据需要创建任意数量的分组项目。

于 2012-02-17T09:35:35.143 回答
0

只是为了回答我自己的问题:泡菜

于 2009-11-23T12:43:20.930 回答