LoginSignup
7
2

More than 3 years have passed since last update.

Rails に CircleCIを導入する

Posted at

はじめに

Rails に CircleCI を導入して GitHub に push すれば自動でテストなどが走るようにしていきます。

手順

  1. CircleCI の自分のアカウントで CI を走らせたいリポジトリを選択
  2. .circleci 以下に config.yml を作成
  3. push する

実装

Rails のアプリ作成(MySQLで作ります。)

$ rails new circleci_practice -d mysql

scaffoldで適当なCRUDを作成します。

circleci_practic $ rails g scaffold users name:string email:string

Gemfile に rspec を追加し bundle install

適当な RSpec を一つ書いてみてください。

.circleci ディレクトリを作り config.yml を作成

そのままでは Docker上でMySQLに接続できないのでhostの部分を編集してください。
とりあえず以下のような感じでいいと思います。

confg/database.yml
test:
  <<: *default
  database: circleci_parctice_test
  # ↓これを追加
  host:  <%= ENV['DATABASE_HOST'] } %>
circleci/config.yml
version: 2

jobs:
  test:
    docker:
      - image: circleci/ruby:2.7.1-node
        environment:
          RAILS_ENV: test
          DATABASE_HOST: 127.0.0.1 
      - image: circleci/mysql:5.7
        environment:
          MYSQL_ALLOW_EMPTY_PASSWORD: true
          MYSQL_ROOT_PASSWORD: ''
          MYSQL_DATABASE: circleci_parctice_test
    working_directory: ~/circleci_parctice
    steps:
      - checkout
      - run:
          name: "bundle install"
          command: bundle install --path vendor/bundle
      # MySQLと接続できるまで待ちます
      - run:
          name: "waiting DB start"
          command: dockerize -wait tcp://127.0.0.1:3306 -timeout 1m
      - run:
          name: "initialize DB"
          command: |
            bundle exec rake db:create
            bundle exec rake db:migrate
      - run:
          name: RSpec
          command: bundle exec rspec


workflows:
  version: 2
  workflows:
    jobs:
      - test

これで push すると自動でCIが走ると思います。

おわりに

他にも rubocop を入れたり、 slim-lint を入れたりするといい感じになると思います。
yarn install や bundle install で cache を使ったりすると速くなります。

7
2
0

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
7
2