Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ybart/8844969 to your computer and use it in GitHub Desktop.
Save ybart/8844969 to your computer and use it in GitHub Desktop.
# 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
# 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
class FactoryGirl::DefinitionProxy
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) do |instance, evaluator|
yield instance, evaluator
end
# after_create will be called after after_build if the build strategy is Factory.create()
after(:create) do |instance|
instance.send(collection).each { |i| i.save! }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment