Skip to content

Instantly share code, notes, and snippets.

@coorasse
Forked from renius/fg_find_or_create.rb
Last active December 28, 2017 16:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save coorasse/c9034a484eaf32fa6556 to your computer and use it in GitHub Desktop.
Save coorasse/c9034a484eaf32fa6556 to your computer and use it in GitHub Desktop.
module FactoryGirl
module Syntax
module Methods
def find_or_create(name, attributes = {}, &block)
attributes = FactoryGirl.attributes_for(name).merge(attributes)
klass = FactoryGirl.factory_by_name(name).build_class
enums = klass.defined_enums
find_attributes = attributes.clone
find_attributes.keys.each do |key|
find_attributes[key] = enums[key.to_s][find_attributes[key]] if enums.has_key? key.to_s
end
result = klass.find_by(find_attributes, &block)
result || FactoryGirl.create(name, attributes, &block)
end
end
end
end
@maunovaha
Copy link

A fork which works with factory girl traits https://gist.github.com/maunovaha/c9a32e217f5dab5d45a7055c69460e21

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