Skip to content

Instantly share code, notes, and snippets.

@mguymon
Last active January 27, 2016 07:27
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 mguymon/5920615 to your computer and use it in GitHub Desktop.
Save mguymon/5920615 to your computer and use it in GitHub Desktop.
RSpec helper for adding find_or_create to FactoryGirl for Rails
module FactoryGirlHelper
def find_or_create(*args)
name = args.shift
clazz = nil
# convert from underscores String to camelcase Class
if name.is_a? Hash
name = name.first[0]
clazz = name.first[1].to_s.camelize.constantize
else
clazz = name.to_s.camelize.constantize
end
target = nil
# Create Arel lookup to see if model already exists
lookup = args.shift
unless lookup.empty?
target = clazz.where(lookup).first
end
# IF the model was not found, create a new one
if target.nil?
target = FactoryGirl.create(name,lookup)
end
target
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment