简体   繁体   中英

How to set up test database configuration in Rails

I am working on existing rails project and just finished writing some basic RSpec tests for that. In our database.yml file we have connection to 3-4 different databases and all are either pointing to either production database or staging database. For testing environment I created a different yml file called database.test.yml and then symlinked it to database.yml file, so that the correct testing databases connections are created.

My database.test.yml looks something like this:

abc:
  adapter: mysql2
  host: localhost
  reconnect: true
  username: monty
  password: python
  database: abc

pqr:
  adapter: mysql2
  host: localhost
  reconnect: true
  username: monty
  password: python
  database: pqr

test:
  adapter: mysql2
  host: localhost
  reconnect: true
  username: monty
  password: python
  pool: 50
  database: testing

My problem now is that how can I enforce that other developers/testers use this database.test.yml and not accidentally run the main database.yml file which contains connections to staging and production databases.

EDIT:

To further clarify my question, I have establish_connection in various models that connect to different databases. So I am not sure the earlier suggestions will solve my problem.

Example:

class Abc < ActiveRecord::Base
  establish_connection :abc
end

One way I can think of for solving my problem is doing something like this:

class Abc < ActiveRecord::Base
  establish_connection "abc_#{Rails.env}"
end

and in the database.yml :

defaults: &defaults
  adapter: mysql2
  encoding: utf8
  username: root
  password: secret

abc_production:
  database: abc
  <<: *defaults

abc_development:
  database: abc_devlopment
  <<: *defaults

abc_test:
  database: abc_test
  <<: *defaults

But I am not sure if this the best practice and I really don't feel to change the application code to setup test environment is good practice. This idea is based on: http://blog.nistu.de/2012/03/25/multi-database-setup-with-rails-and-rspec

Any nudge or pointers towards the correction direction will be greatly helpful.

You could have something, like:

default: &default
  adapter: mysql2
  encoding: utf8
  database: my_db_name
  username: root
  password: my_password
  host: 127.0.0.1
  port: 3306

development:
  <<: *default
  database: xxxx_development

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: xxxx_test

production:
  <<: *default
  database: xxxx_production

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM