Rails, factory_girl and has_many
This is just a quick note that some people might find useful. I do not write factory_girl Factories that often and when I do I always keep its RDoc opened up because I never seem to remember the API (after not using it for a while).
The problem I had few times before and the problem I set out to fix today was: “What to do when you want to create multiple objects for your has_many association?” Now, this seems like a simple task for factory_girl callbacks. I tried many approaches, this is my final one and I am happy it works.
Lets say we have a model Bundle and it has_many BundleItems. Then a factory that creates a Bundle with exactly four BundleItems will look like this:
Factory.define :bundle do |f|
f.bundle_items do |bundle|
res = []
4.times do
res << Factory.build(:bundle_item, :bundle => bundle.result)
end
res
end
end
The only thing I am quite unhappy about is that this calls Proxy.result sooner than it would originally happen, but I simply do not see a better way around this. Suggestions are welcome!
Thanks for posting this. It helped me.
A quick tip: you can combine the enumerators to convert your bundle items block into a single line:
4.times.map { Factory.build(:bundle_item, :bundle => bundle.result) }.