Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
# 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:
class Factory
def has_many(collection)
# after_build is where you add instances to the factory-built collection.
# Typically you'll want to 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|! }
# Usage
# Foo has_many :bar
Factory.define :foo do |f|
f.has_many :bar do |foo| <<, :foo => foo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment