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.
def 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
@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