Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

factory girl and nested_attributes in rails 3

I have 2 models, one which accepts attributes for the other and I'm trying to find a clever way to use Factory girl to setup the data for both.

Class Booking
has_many :booking_items
accepts_nested_attributes_for :booking_items

Class BookingItem
belong_to :booking

my factory

Factory.define :booking do |f|
  f.bookdate Date.today+15.days
  f.association :space
  f.nights 2
  f.currency "EUR"
  f.booking_item_attributes Factory.build(:booking_item) # doesn't work
end

Factory.define :booking_item do |f|
  f.association :room
  f.bookdate Date.today
  f.people 2
  f.total_price 20
  f.association :booking
end

booking_spec

require "spec_helper"

describe Booking do

  before(:each) do
    @booking = Factory.create(:booking)
  end

  it "should be valid" do
    #needs children to be valid
    @booking.should be_valid
  end


end

I looked around the rdocs but couldn't seem to find what I was looking for.

like image 736
holden Avatar asked Feb 25 '23 11:02

holden


1 Answers

If I understood you correctly, you want to do this, but with terser syntax:

booking_item = Factory(:booking_item, :people => 4)
booking = Factory(:booking, :booking_item => booking_item)

Of cause you can shortcut it like this:

def with_assocs factory, assocs_hashes = {}, attrs = {}
  assoc_models = Hash[ assocs_hash.map { |k, v| [k, Factory(k, v)] } ]
  Factory factory, attrs.merge(assoc_models)
end

And use like this:

@booking = with_assocs :booking, :booking_item => {:people => 3}
@booking.should be_valid

In active_factory plugin with similar factory definitions it would look like this:

models { booking - booking_item(:people => 3) }
booking.should be_valid

Unfortunately I haven't yet implemented integration with factory_girl. Though if you interested any input is very welcome.

like image 90
Alexey Avatar answered Mar 08 '23 09:03

Alexey