我有一个访问两个数据库的Rails应用程序:读取副本,它是通过标准database.yml
文件配置的数据库。
有某些访问读取副本的模型,我使用establish_connection
动态切换到副本:
class MyReadReplicaDbBase < ActiveRecord::Base
self.abstract_class = true
establish_connection READ_REPLICA_DB
end
class User < MyReadReplicaDbBase
end
实际环境与此设置很好地运行,但是在Travis进行测试时,我需要使用这样的方法设置两个数据库:
language: ruby
cache: bundler
rvm:
- 2.5.1
services:
- docker
- redis-server
env:
global:
- DB_URL=postgres://postgres@localhost/travis_ci_test
- READ_REPLICA_DB_URL=postgres://postgres@localhost/travis_ci_read_replica_test
# https://github.com/travis-ci/travis-ci/issues/9624#issuecomment-389537036
before_install:
- sudo sed -i -e '/local.*peer/s/postgres/all/' -e 's/peer|md5/trust/g' /etc/postgresql/*/main/pg_hba.conf
- sudo service postgresql restart
- sleep 1
- gem update --system
- gem install bundler
sudo: required
dist: xenial
addons:
postgresql: "10"
apt:
packages:
- postgresql-10
- postgresql-client-10
env:
global:
- PGPORT=5433
before_script:
- cp config/database.yml.travis config/database.yml
- psql -c 'create database travis_ci_test;' -U postgres
- psql -c 'create database travis_ci_read_replica_test' -U postgres
script:
- bundle exec rails db:migrate RAILS_ENV=test
- bundle exec rspec -f d
是否有标准方法可以在复制数据库中加载模式进行测试?我可以运行以下内容吗?
rake:db:schema:load --database read_replica_db
我知道这是行不通的,因为它会将默认环境设置为设置该数据库。
,所以我使用个人访问令牌来工作并使用此脚本复制模式
#load_read_replica_schema.rb
#!/home/travis/.rvm/rubies/ruby-2.5.1/bin/ruby
def install_gems()
system('gem install pg')
system('gem install activerecord -v=5.2.2')
end
def get_read_replica_schema_file
require 'active_record'
require 'active_record/tasks/database_tasks'
require 'active_record/tasks/postgresql_database_tasks'
curl_command = "curl -s https://#{ENV['PERSONAL_ACCESS_TOKEN']}@raw.githubusercontent.com/<owner>/<repo>/master/db/schema.rb -o read_replica_schema.rb"
system(curl_command)
ActiveRecord::Tasks::DatabaseTasks.load_schema('postgres://postgres:@localhost/travis_ci_read_replica_test', :ruby, 'read_replica_schema.rb', :test)
end
install_gems()
get_read_replica_schema_file()
类似地更新了带有脚本的travis.yaml脚本上的脚本
before_script:
- cp config/database.yml.travis config/database.yml
- psql -c 'create database travis_ci_test;' -U postgres
- psql -c 'create database travis_ci_read_replica_test' -U postgres
script:
- ./load_read_replica_api_schema.rb
- bundle exec rails db:migrate RAILS_ENV=test
- bundle exec rspec -f d