Skip to content

Instantly share code, notes, and snippets.

@Aerlinger
Last active February 3, 2017 14:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Aerlinger/ba8fe98fb58ec6be4d6f to your computer and use it in GitHub Desktop.
Save Aerlinger/ba8fe98fb58ec6be4d6f to your computer and use it in GitHub Desktop.
find_or_create with factory girl
module FactoryGirl
def self.find_or_create(resource_name, attributes = {}, &block)
clazz = resource_name.to_s.classify.constantize
model = clazz.find_by(attributes) || FactoryGirl.build(resource_name, attributes)
yield(model) if block_given? && model.new_record?
model.tap(&:save)
end
end
@abinoam
Copy link

abinoam commented Nov 24, 2014

Great!

@abinoam
Copy link

abinoam commented Dec 5, 2014

Dear @Aerlinger,

I've made a small modification on your gist. https://gist.github.com/abinoam/4ab40317ef9d1424d808
Now I can use include FactoryGirl::Syntax::Methods as the official FactoryGirl documentation in http://www.rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment