开发者

What's the best practice for setting up associations with factory_girl in cucumber?

I normally use this step to set up records with factory_girl:

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

And here's my work-around when setting up associations:

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

I know this is bad. Using ids makes the whole开发者_如何转开发 thing brittle and cryptic from the vantage of the domain person.

So, my question is -- what would be the best practice to set up an association with factory_girl and a table argument like the one above?


You can define multiple associations in a factory.
Like the following :

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

Doing a Factory(:group) will create your group uplet with two items in it.


Just to answer my own question: Pickle


You can use the defined FactoryGirl Cucumber steps:
https://github.com/thoughtbot/factory_girl/blob/master/lib/factory_girl/step_definitions.rb

You can setup your items and your group(s) in just one Cucumber step:

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

When doing it like this, the creation of group 'Bar' is using 'find_or_create_by' functionality, so the first call creates the group, the next 2 calls finds the already created group.

In this way all 3 items will have same group 'Bar', and you can create as many grouped items as you need.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜