Last active
          January 27, 2016 07:27 
        
      - 
      
- 
        Save mguymon/5920615 to your computer and use it in GitHub Desktop. 
    RSpec helper for adding find_or_create to FactoryGirl for Rails
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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