やりたいこと
最新(9.4)のPostgreSQLを使ったRails appをTravisCIでテストしたい。
手元で使ってるSQLite3もついでにテストしておく。
MySQLは一旦おいとく。
手順
Gemfile(抜粋)
group :development, :test do
gem 'sqlite3', '~> 1.3.10'
end
group :production, :test do
gem 'pg', '~> 0.17.1'
end
:test
グループで sqlite3
と pg
がインストールされるようにする。手元のMacで動かすために brew install postgresql
が必要になってしまったのが難点ではある。
config/database.travis.yml
TravisCI用の database.yml
を用意しておいて、テスト実行前にコピーする。
config/database.travis.yml
sqlite: &sqlite
adapter: sqlite3
database: db/<%= Rails.env %>.sqlite3
postgresql: &postgresql
adapter: postgresql
username: postgres
password:
database: YOUR_APP_NAME_<%= Rails.env %>
min_messages: ERROR
defaults: &defaults
pool: 5
timeout: 5000
host: localhost
<<: *<%= ENV['DB'] || "postgresql" %>
development:
<<: *defaults
test:
<<: *defaults
production:
<<: *defaults
.travis.yml
(抜粋)
事前処理をいろいろ指定している。
-
before_install
: PostgreSQL 9.4をインストール- 走ってるpostgresqlを止める
- PostgreSQL 9.1〜9.3を削除
-
pg_hba.conf
を書き換え- http://www.postgresql.org/docs/9.4/static/auth-pg-hba-conf.html
- デフォルトではUnixユーザとpostgresのユーザ名が違うと怒られる
-
env
: sqliteとpostgresqlでテストするよ、と宣言 -
script
: テストを実行するコマンド -
before_script
: テスト実行前の操作-
config/database.travis.yml
をコピー - テスト用データベースを作成
-
travis.yml
before_install:
- sudo /etc/init.d/postgresql stop
- sudo apt-get update
- sudo apt-get purge postgresql-9.1 postgresql-9.2 postgresql-9.3
- sudo apt-get language-pack-es postgresql-9.4
- sudo chmod 777 /etc/postgresql/9.4/main/pg_hba.conf
- sudo echo "local all postgres trust" > /etc/postgresql/9.4/main/pg_hba.conf
- sudo echo "local all all trust" >> /etc/postgresql/9.4/main/pg_hba.conf
- sudo echo "host all all 127.0.0.1/32 trust" >> /etc/postgresql/9.4/main/pg_hba.conf
- sudo echo "host all all ::1/128 trust" >> /etc/postgresql/9.4/main/pg_hba.conf
- sudo /etc/init.d/postgresql restart
- psql --version
env:
- DB=sqlite
- DB=postgresql
script:
- RAILS_ENV=test bundle exec rake db:migrate --trace
- bundle exec rake db:test:prepare
- bundle exec rake
before_script:
- cp config/database.travis.yml config/database.yml
- psql -c 'create database YOUR_APP_NAME_test' -U postgres
参考リンク
- http://stackoverflow.com/questions/9321153/rails-database-setup-on-travis-ci
- http://docs.travis-ci.com/user/using-postgresql/
- https://github.com/travis-ci/travis-ci/issues/2983
- https://code.google.com/p/plv8js/source/browse/.travis.yml
ひとりごと
- HerokuはまだPostgreSQLが9.3なので、Travisで用意されている9.3を使えば簡単だったはず
- でも近いうちに上がるだろうし、9.4でやらない理由はない
- …と思ったらわりといらない苦労をしてしまった