Here are the model relationships:
class Tool < ActiveRecord::Base
...
has_many :loss_ratios, :dependent => :destroy, :order => "loss_ratios.starts_at DESC"
validates_associated :loss_ratios
accepts_nested_attributes_for :loss_ratios, :allow_destroy => true
attr_accessible :name, :text, :service_id, :supplier_id, :loss_ratios_attributes
end
class LossRatio < ActiveRecord::Base
belongs_to :tool
validates :rate, :starts_at, :tool, :presence => true
validates_uniqueness_of :starts_at, :scope => :tool_id
validates_numericality_of :rate
validates_inclusion_of :rate, :in => (0..1)
...
end
I’m managing LossRatio associations in the create/update ToolsController actions. I want to test those by POSTing sets of attributes for a Tool (including a couple of nested LossRatios as though they were submitted in a form). I’m using FactoryGirl, but it doesn’t seem to have a way of constructing a params-like hash of attributes (attributes_for ignores associations, and looks like this behavior is not gonna change).
Is there a way to do this?
(I know the title is a mess, but I couldn’t think of anything better and shorter…)
OK here’s what I’ve come up with after pulling my hair out for half a day:
This is a helper method used for building a params hash consumable by a controller’s CRUD actions. I’m using it in my controller specs like so:
As seen from the snippet, the method only populates attributes for has-many associations (and ignores has-many-through associations). I guess it might be extended for any kind of relationships, but that works for me so far (unless there’s a better way of doing what I want)…