Index

一週間のカリキュラム 1週間で、Ruby 〜 Ruby on Railsまでを学ぶ

シリーズの6日目、テストを書く,CIを回す,自動デプロイについて見ていきます。。

6日目


1 テストとは

テストの形式に関しては テストとは をご覧ください。

今回は単体テストを取り扱います。


 2 Railsにおける テスト

Rails標準のMinitestとGemを入れて使うRspecがあります。 期の段階ではどちらを利用しても問題ないが、Rspecの方が日本語ドキュメントは多いです。

Minitest参照

Rspec

今回はRails標準のMinitestでテストを書いてみます。


3 Minitesの動作確認

3-0 deviceによって作成されたファイル

test/fixtures/users.yml 一旦このファイルは削除しておきましょう。

今後ユーザーのテストが必要になった場合は再度作成しましょう。

3-1 簡単なテスト

まずは簡単なエラーになるテストを書きます。

test/models/article_test.rb

#エラーになるテスト
test "should not save article without title" do
  article = Article.new
  assert_not article.save
end

テスト実行

全てテスト
$ bin/rails test

個別にテスト
$ bin/rails test test/models/article_test.rb

3-2 モデルのバリデーションをテストしてみる。

今度はしっかり動くようにテストしてみます。

test/models/article_test.rb

require 'test_helper'

class ArticleTest < ActiveSupport::TestCase
  def setup
    # Fixtureからカテゴリー :oneを取り出しています。
    @category = categories(:one)

    # それを利用して記事を新規に作成します。
    @article = Article.new(title: 'test titles2 ', body: 'ここは10文字必要', category_id: @category.id)
  end

  test 'should be valid' do
    # 今設定されてるバリデーションが機能してるか確認してます。
    e = @article.valid?
    # 一応エラーメッセージも表示しておきます。
    puts @article.errors.messages
    # 記事body部分が10文字以下なので エラーが発生してる = テスト成功となります。
    assert_not e
  end
end

カテゴリ部分はFixtureという仕組みをつかってあらかじめ、DBを参照するかのような 書き方になっています。

test/fixtures/categories.yml

# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html

one:
  name: Category1

two:
  name: Category2

3-3 テストを動かしてみましょう。

個別にテスト
$ bin/rails test test/models/article_test.rb

Running 1 tests in a single process (parallelization threshold is 50)
Run options: --seed 28672

# Running:

{:body=>["is too short (minimum is 10 characters)"]}
.

Finished in 0.103852s, 9.6291 runs/s, 9.6291 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips

バリデーションエラーしてる=テスト成功の確認ができました。

3-4 全体をテストしてみましょう。

$ bin/rails test


4 rubocopでを動かしましょう。

文法チェック、lint機能としてrubocopを利用します。

$ rubocop

修正すべき文法的な部分を指摘してくれます。 F,E,Wなどの、エラーがある箇所に関しては対応をしましょう。

完全修正対象
F Fatal
E Error
W Warning

考慮、修正の余地
C Convention
R Refactor

手作業で無くとも -aオプションで自動で修正をしてくれます。

$ rubocop -a

lintして自動修正を動かします。 残った物が、基本CやRだけならば、一旦放置してもOKです。


5 CIを回す。

パターンはいくつかあります。

  • ローカル環境でコミット前にテスト

pre-commitというツールを利用して、コミットと同時にテストを走らせてリする事が可能です。 参考

こちらに関してては今回一旦スルーします。

  • Githubなどで、任意のタイミングでCIツールと連携してテストを回す。

今回は、こちらを進めます。

5-1 Githubに自分のリポジトリを登録

Githubアカウントを準備して、今まで利用してたリポジトリを登録します。

登録後 ActionでRailsを検索してください。

これを、そのままGithubの画面からコミットして追加します。

※このままだとエラーを起こすの、lint部分を変更します。

# This workflow uses actions that are not certified by GitHub.  They are
# provided by a third-party and are governed by separate terms of service,
# privacy policy, and support documentation.
#
# This workflow will install a prebuilt Ruby version, install dependencies, and
# run tests and linters.
name: "Ruby on Rails CI"
on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:11-alpine
        ports:
          - "5432:5432"
        env:
          POSTGRES_DB: rails_test
          POSTGRES_USER: rails
          POSTGRES_PASSWORD: password
    env:
      RAILS_ENV: test
      DATABASE_URL: "postgres://rails:password@localhost:5432/rails_test"
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      # Add or replace dependency steps here
      - name: Install Ruby and gems
        uses: ruby/setup-ruby@8f312efe1262fb463d906e9bf040319394c18d3e # v1.92
        with:
          bundler-cache: true
      # Add or replace database setup steps here
      - name: Set up database schema
        run: bin/rails db:schema:load
      # Add or replace test runners here
      - name: Run tests
        run: bin/rake

  lint:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      - name: Install Ruby and gems
        uses: ruby/setup-ruby@8f312efe1262fb463d906e9bf040319394c18d3e # v1.92
        with:
          bundler-cache: true
      # Add or replace any other lints here
      # - name: Security audit dependencies
      #  run: bin/bundler-audit --update
      # - name: Security audit application code
      #  run: bin/brakeman -q -w2
      - name: Lint Ruby files
        #run: bin/rubocop --parallel
        uses: reviewdog/action-rubocop@v1
        with:
          rubocop_version: gemfile
          rubocop_extensions: rubocop-rails:gemfile
          github_token: ${{ secrets.github_token }}
          reporter: github-pr-review


5-2 さっそくActionの画面を見ると

lint
input ruby-version needs to be specified if no .ruby-version or .tool-versions file exists

test
上と同じメッセージ

が出てきます。

これは .ruby-versionというファイルを作成し バージョンを明記しろという指示です。

Github側でリポジトリが変更されてるので、一度リモート(Github)の変更を手元の環境に取り込みます。

$ git pull

 .github/workflows/rubyonrails.yml | 58 ++++++++++++++++++++++++++++1 file changed, 58 insertions(+)

先程の指示があったファイルを作成します。

.ruby-version

3.1.0

変更後にpushしましょう。 git push -u origin main

あとで確認 あとで確認2


6 Herokuへのデプロイ

HerokuからDeployをメニューを選ぶ

Githubを選択して、認証作業を行う。

デプロイブランチを指定、CI待ちにチェックボックスにチェックを入れる。

これで自動でデプロイが可能になる。

※管理画面からブランチを選んでマニュアルでのデプロイも出来る。

最新記事一覧

続きを見る

関連コンテンツ

カテゴリー一覧

TOP フルスタックエンジニアを目指すに方々へ 2022年2月6日 CRUDについて