Skip to content

Instantly share code, notes, and snippets.

@renius
Forked from thewatts/fg_find_or_create.rb
Last active October 31, 2017 15:18
Show Gist options
  • Save renius/9af62ff8d68a932a8895 to your computer and use it in GitHub Desktop.
Save renius/9af62ff8d68a932a8895 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)
result =
FactoryGirl.
factory_by_name(name).
build_class.
find_by(attributes, &block)
result || FactoryGirl.create(name, attributes, &block)
end
end
end
end
@TurtleShip
Copy link

Hi, thanks for putting up this gist!

This helped me a lot. I've put this code inside spec/rails_helper.rb. I am a factory_girl noob, and I am sure there is a better place to put this code.

Where can I put this code?

Thanks in advance!

@coorasse
Copy link

a fork which works with enums as well https://gist.github.com/coorasse/c9034a484eaf32fa6556

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