Skip to content

Instantly share code, notes, and snippets.

@thewatts
Forked from abinoam/fg_find_or_create.rb
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 thewatts/dcc91ef40b144aff42ae to your computer and use it in GitHub Desktop.
Save thewatts/dcc91ef40b144aff42ae to your computer and use it in GitHub Desktop.
module FactoryGirl::Syntax::Methods
def find_or_create(name, attributes = {}, &block)
factory = FactoryGirl.factory_by_name(name)
klass = factory.build_class
factory_attributes = FactoryGirl.attributes_for(name)
attributes = factory_attributes.merge(attributes)
result = klass.find_by(attributes, &block)
if result
result
else
FactoryGirl.create(name, attributes, &block)
end
end
end
@renius
Copy link

renius commented May 29, 2015

@samlehman
Copy link

thanks, exactly what I needed

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