How to selectively disconnect a remote db connection during rspec tests?

I have a configuration in which, in addition to the local postgresql database, my Rails application also accesses the remote AWS database. My problem is that even in tests that are not connected to the remote database, the application connects to the remote database every time, so my tests are executed sloooooowly.

Is there a clean way to disable access to a remote database server for rspec tests that it does not need? (And turn it on for the tests he needs?)

The best I can think of is to split my rspec tests into two separate parts - those that don't need access to remote db and what they do - and use environment variables to enable or disable parts of the configuration / database .yaml respectively.

To make this clear, my file config/database.yamlcontains (partially):

# file: config/database.yaml

# Define connections to the external database
remote:
  adapter: mysql
  database: remote
  username: <%= ENV['PRODUCTION_DB_USERNAME'] || 'root' %>
  password: <%= ENV['PRODUCTION_DB_PASSWORD'] || '' %>
  host: awsserver-production-mysql.abcdef1234567890.us-west-2.rds.amazonaws.com
  port: 3306

test:
  adapter: postgresql
  encoding: unicode
  database: MyApp_test
  pool: 5
  username: <%= ENV['POSTGRESQL_DB_USERNAME'] || 'MyApp' %>
  password: <%= ENV['POSTGRESQL_DB_PASSWORD'] || '' %>

(NOTE: If you are interested, using mocks will not help: a remote db connection is established even before the tests are run. And vcr only intercepts HTTP connections - database connections use a different mechanism.)

Update

I found examples of how to dynamically establish a connection:

def connect_to_myapp_database
  ActiveRecord::Base.establish_connection(:adapter => "mysql",
                                          :database => 'myapp',
                                          :username => ENV['MYAPP_DB_USERNAME'],
                                          :password => ENV['MYAPP_DB_PASSWORD'],
                                          :host => 'mayapp-mysql.abcdefg123456.us-west-2.rds.amazonaws.com',
                                          :port => 3306,
                                          )
end

- , . : , ?

+4
1

nulldb gem.

Gemfile:

group :development, :test do
  gem 'activerecord-nulldb-adapter', :git => 'git://github.com/nulldb/nulldb.git'
end

bundle install

, :

class ExternalModel < ActiveRecord::Base
  unless Rails.app.test?
    establish_connection(:myapp)
  else
    establish_connection(:adapter => :nulldb)
  end

  def readonly?; true; end
end

ExternalModel ( ):

class ExternalUser < ExternalModel
  ...
end

. , ExternalUser , .

, .

+2

All Articles