How to set up factory in FactoryGirl with has_many association

Alternatively, you can use a block and skip the association keyword. This makes it possible to build objects without saving to the database (otherwise, a has_many association will save your records to the db, even if you use the build function instead of create).

FactoryGirl.define do
  factory :listing_with_features, :parent => :listing do |listing|
    features { build_list :feature, 3 }
  end
end

Creating these kinds of associations requires using FactoryGirl's callbacks.

A perfect set of examples can be found here.

https://thoughtbot.com/blog/aint-no-calla-back-girl

To bring it home to your example.

Factory.define :listing_with_features, :parent => :listing do |listing|
  listing.after_create { |l| Factory(:feature, :listing => l)  }
  #or some for loop to generate X features
end

You could use trait:

FactoryGirl.define do
  factory :listing do
    ...

    trait :with_features do
      features { build_list :feature, 3 }
    end
  end
end

With callback, if you need DB creation:

...

trait :with_features do
  after(:create) do |listing|
    create_list(:feature, 3, listing: listing)
  end
end

Use in your specs like this:

let(:listing) { create(:listing, :with_features) }

This will remove duplication in your factories and be more reusable.

https://robots.thoughtbot.com/remove-duplication-with-factorygirls-traits