Question

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?

Was it helpful?

Solution 2

Just to answer my own question: Pickle

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top