Passing single attributes to associated factories

Posted by lambdabutz on Stack Overflow See other posts from Stack Overflow or by lambdabutz
Published on 2010-06-14T20:27:45Z Indexed on 2010/06/14 20:32 UTC
Read the original article Hit count: 294

Filed under:
|

I'm looking for a way to pass fields into the factories of associated models without having to explicitly call the factory itself.

For example, lets say I have some factories like so:

Factory.define :person do |person|
  person.name  "Default Bob"
  person.sex   "M"
  person.house {|p| p.association(:house)}
end

Factory.define :house do |house|
  house.color  "Red"
  house.has_ac true
  house.suburb {|h| h.association(:suburb)}
end

Factory.define :suburb do |suburb|
  suburb.name  "Little boxes"
end

This is fine and all, but if I want to use factories to create someone in a specific house in a specific suburb I have do this:

sub = Factory(:suburb, :name => "Blue town")
house = Factory(:house, :color => "Blue", :suburb => sub)
person = Factory(:person, :name => "Bill", :house => house)

While this isn't bad in this small case, my actual models sometimes have 7 or 8 associations, and when I want to create an object whose associations I only care about a single attribute, the code for this starts to get really heavy. Is there somewhat I can pass attributes to nested Factories without having to recall the Factory itself?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about factorygirl