Rails 開発で GitHub に Push して CircleCI のテストが通ったら Heroku に deploy する

CircleCI を使って、テストが通ったら Heroku に deploy するという流れを構築する。

サンプルリポジトリ: starhoshi/rails-circleci

環境

  • GitHub
  • Rails 5.X
  • Heroku
  • CircleCI 1.X
    • ここでのサンプルは 2.0 ではない

ソースコードstarhoshi/rails-circleci

まず rails new

$ gem install rails
$ rails new . --api -d=postgresql
$ rails g controller

これで Rails Project + users_controller が作成される。
また、コメントアウトされている test のコメントを外し、通るようにする。

test/controllers/users_controller_test.rb

require 'test_helper'

class UsersControllerTest < ActionDispatch::IntegrationTest
  test "the truth" do
    assert true
  end
end

GitHub に Push

GitHub に Repository を作って、 Push しておく

CircleCI と Repository の連携

CircleCI に GitHub でログインしておく。
CircleCIでRails4アプリをHerokuへデプロイする - Qiita にあるように、 ssh key の登録が必要かもしれない。

Projects > Add Project > rails-circleci を Set Up する。

f:id:star__hoshi:20171126170222g:plain

そうすると勝手に CircleCI が回り出して、テストが成功する。

Heroku

Heroku App 作成

こんな感じで作成する。

f:id:star__hoshi:20171126170458p:plain

API Key

https://dashboard.heroku.com/account から API Key を取得

f:id:star__hoshi:20171126170540p:plain

CircleCI の Heroku Deployment 設定

https://circleci.com/account/heroku に取得した API Key を設定する。

f:id:star__hoshi:20171126170746g:plain

これで Heroku / CircleCI の設定が完了。

circle.yml

deployment:
  production:
    branch: master
    commands:
      - heroku maintenance:on --app rails-circleci
      - git push git@heroku.com:rails-circleci.git $CIRCLE_SHA1:refs/heads/master
      - heroku run 'rake db:migrate; rake db:seed_fu' --app rails-circleci
      - heroku maintenance:off --app rails-circleci

こんな感じで作成。 --app と git@heroku.com:rails-circleci.git は自分の環境に合わせる。

git push すると CircleCI が動いて Heroku Deploy される

git push すると自動で CircleCI が動いて、 test が実行されたあとに deploy される。

f:id:star__hoshi:20171126171100p:plain

これでめでたく当初やりたかったことができた。

test がコケたらどうなる?

Not Deploying になって、 deploy がされないことがわかる。

f:id:star__hoshi:20171126171248p:plain