fivetwentysix
fivetwentysix

Reputation: 7487

Using FactoryGirl, how would I insert accepts_nested_attributes_for children attributes into the object I'm creating?

factory :payment_object do
  company_id 1
  user_id 1
  delivery_date (Date.today + 1)
  payment_terms 'CBD'
  vendor 'Apple'
  currency 'USD'

  # item
    # name "Macbook"
    # quantity 1
    # price 1000
  # item
    # name "Magic Mouse"
    # quantity 1
    # price 65   
end

Upvotes: 2

Views: 1533

Answers (2)

Magne
Magne

Reputation: 17223

It's unintuitive, but the factory_girl docs states how, when you search for 'has_many': https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md

Basically, first, make another factory:

FactoryGirl.define do
  factory :item do
    name "Macbook"
    quantity 1
    price 1000
    payment_object
  end
end

Then use that within your code, like this:

FactoryGirl.define do
  factory :payment_object do
    company_id 1
    user_id 1
    delivery_date (Date.today + 1)
    payment_terms 'CBD'
    vendor 'Apple'
    currency 'USD'

    # This is how you reference the list with your items
    ignore do
      items_count 5  # the number items that should be in the list
    end
    after(:create) do |payment_object, evaluator|
        FactoryGirl.create_list(:item, evaluator.items_count, payment_object: payment_object)
    end


  end

Upvotes: 1

fivetwentysix
fivetwentysix

Reputation: 7487

Here's a way you can do it inside your specs.

before(:each) do
  @payment_object = FactoryGirl.build(:payment_object)
  5.times do 
    @payment_object.items << FactoryGirl.build(:item)
  end
  @payment_object.save!
end

Upvotes: 2

Related Questions