Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save softcraft-development/436917 to your computer and use it in GitHub Desktop.

Select an option

Save softcraft-development/436917 to your computer and use it in GitHub Desktop.

Revisions

  1. softcraft-development created this gist Jun 13, 2010.
    30 changes: 30 additions & 0 deletions add_collection_associations_to_factory_girl_factories.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    # Goal: Allow addition of instances to a collection in a factory-built object
    # when those instances require references to the parent.
    # Typically occurs in Rails when one model has_many instances of another

    # See more at:
    # http://stackoverflow.com/questions/2937326/populating-an-association-with-children-in-factory-girl

    class Factory
    def has_many(collection)
    # after_build is where you add instances to the factory-built collection.
    # Typically you'll want to Factory.build() these instances.
    after_build { |instance|
    yield instance
    }

    # after_create will be called after after_build if the build strategy is Factory.create()
    after_create { |instance|
    instance.send(collection).each { |i| i.save! }
    }
    end
    end

    # Usage
    # Foo has_many :bar

    Factory.define :foo do |f|
    f.has_many :bar do |foo|
    foo.bar << Factory.build(:bar, :foo => foo)
    end
    end