thoughtbot/factory_girl — Issue #230: More documentation needed for complex (real-world) model schema
Author: gamov
Created: 2011-11-08 05:11:49+00:00
State: open

Hello,
I'm trying to embrace factories to replace my fixtures. I have around 50 models and my fixtures represent a coherent, valid state of the system where almost every case is showcased.
I've been trying to reproduce this with factory_girl but I reached a point where I need help, the documentation does not depict this kind of situation. I'll update the doc with the help I gather here (similarly as issue #202 on has_many associations). I also wonder if I could link from the doc to relevant Smashing Robots blog entries.

This is where I get stuck converting my fixtures to factories:
I have:
* A StockTransfer has_many TransferredItems belongs_to StockItem belongs_to PurchasedItem belongs_to PurchaseOrder
* StockTransfer also belongs to origin_warehouse and destination_warehouse (both Warehouse)
* StockItem also belong_to Warehouse
* All Items belongs_to ItemVariant

I would like to create a factory for a StockTransfer with many TransferredItems but I must respect the following constraints:
* All StockItem (via PurchasedItem) come from the same PurchaseOrder
* The StockItems all come from the same warehouse as the StockTransfer.origin_warehouse
* All chains of items belongs_to the same ItemVariant.

Basically, I wonder the best way to pass parameters through chained associated factories with more than one level deep. In example, I need to tell the nested PurchasedItem that it has the same purchase_order_id as the others.

The only way I currently see is the callbacks where I tweak everything to my constraints but it become just a much of Ruby code that I can put in my tests thus factories lose their utilities...

Your input is very much appreciated.
Gam.