views:

469

answers:

2

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?

+3  A: 

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.

Damien MATHIEU
The trick here is that group.items should return an array. It took me a while to work that out.
jonnii
Yeah that's not easy to understand (but seeing how it works, it's logical)
Damien MATHIEU
Got you. But is there a way to wrap a cucumber step with a table parameter (like the one in my post) around such a factory?Perhaps, I should just take a pragmatic approach and be verbose and specific in the step ("Given I have two items, foo and bar, that belong to a group called foo") instead of fussing with tables, but that sounds somewhat like an anti-pattern to me?
hakanensari
No it's not possible to wrap a cucumber step inside a factory.
Damien MATHIEU
A: 

Just to answer my own question: Pickle

hakanensari