简体   繁体   中英

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.

只是回答我自己的问题: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM