Rails testing – Setup multiple databases when running rake spec

By | October 29, 2013

We currently have 2 databases for our application and I had a need to basically setup both databases, our test database, and another stats database.

I also noticed an issue where running rake spec wouldn’t run in the test environment, which we always wanted it to run it. My solution is the below (Note: We have a db_stats task that basically mimics all the calls of db):

force_rspec_to_test_environment

namespace :db do
  namespace :test do
    
    if db_test_prepare_task.present?
      task :prepare => db_test_prepare_task.prerequisites do
        Rake::Task['db:test:setup'].invoke
      end
    end

    desc "Setup test database - drops, loads schema, and migrates the test db"
    task :setup do 
      if Rails.env.test?
        Rake::Task['db:drop'].invoke
        Rake::Task['db:create'].invoke
        ActiveRecord::Base.connection.execute("CREATE EXTENSION IF NOT EXISTS dblink;")
        Rake::Task['db:migrate'].invoke
        system("rake db_stats:drop RAILS_ENV=test")
        system("rake db_stats:create RAILS_ENV=test")
        SecondDatabaseModel.connection.execute("CREATE EXTENSION IF NOT EXISTS dblink;")
        system("rake db_stats:migrate RAILS_ENV=test")
      else
        system("rake db:test:setup RAILS_ENV=test")
      end
    end
  end
end

def force_rspec_to_test_environment
  unless Rails.env.test?
    rspec_task = Rake.application.instance_variable_get('@tasks')['spec']
    Rake::Task["spec"].clear
    task :spec do
      system("rake spec RAILS_ENV=test")
    end
  end
end

def db_test_prepare_task
  return @db_test_prepare_task if @db_test_prepare_task.present?
  if Rails.env.test?
    @db_test_prepare_task = Rake.application.instance_variable_get('@tasks')['db:schema:load']
    Rake::Task["db:schema:load"].clear
  end
  @db_test_prepare_task
end

Leave a Reply

Your email address will not be published. Required fields are marked *