LoginSignup
6
3

More than 5 years have passed since last update.

Rails app を TravisCI と PostgreSQL 9.4 でテストする

Last updated at Posted at 2015-01-03

やりたいこと

最新(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 グループで sqlite3pg がインストールされるようにする。手元の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をインストール
  • 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

参考リンク

ひとりごと

  • HerokuはまだPostgreSQLが9.3なので、Travisで用意されている9.3を使えば簡単だったはず
  • でも近いうちに上がるだろうし、9.4でやらない理由はない
  • …と思ったらわりといらない苦労をしてしまった :cry:
6
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3