require 'rake'

module JamRuby
  class TestSupport
    
    #helper for resetting test database
    #drop create and execute db migrations
    def self.recreate_database
      ENV['RAILS_ENV'] = 'test'
      Rake.application.init
      Rake.application.load_rakefile
      begin
        Rake::Task['db:jam_ruby:drop'].invoke
        Rake::Task['db:jam_ruby:create'].invoke
        Rake::Task['db:jam_ruby:migrate'].invoke
      rescue ActiveRecord::NoDatabaseError
        puts "Database does not exist. Creating.."
        Rake::Task['db:jam_ruby:create'].invoke
      rescue ActiveRecord::ConnectionNotEstablished
        puts "Database connection error"  
      end
    end

    def self.migrate_database
      ENV['RAILS_ENV'] = 'test'
      # invoke init in this way; otherwise any args passed to rspec will pass through to the rake task and blow it up.
      # for instance, bundle exec rspec spec/some.rb -e "specific test" will cause a weird error
      Rake.application.init('rake', [])
      Rake.application.load_rakefile
      Rake::Task['db:jam_ruby:migrate'].invoke
    end
    
  end
end