Madogiwa Blog

主に技術系の学習メモに使っていきます。

GitHub ActionをRubyとRailsのバージョンのマトリクスで実行するメモ

Gemとかを作るときにRailsのバージョンとサポートしているRubyのバージョンのメトリクスでGitHub ActionでCIを回すときのメモ📝

まず現時点(2022/01/22)のStableのRailsバージョンである7系をインストールするGemfileを用意します。

source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

# Specify your gem's dependencies in aikotoba.gemspec.
gem "rails", "~> 7.0"

Railsは1つ前のメジャーバージョンまでセキュリティパッチのサポートするので6.1系をインストールするGemfileを用意する。このときdependencies.delete_ifを使ってRailsのみを削除して差し替えるようにします。

eval_gemfile File.expand_path("../Gemfile", __dir__)

dependencies.delete_if { |d| d.name == "rails" }
gem "rails", "~> 6.1"

3 セキュリティ問題
現在対象となっているシリーズ: 7.0.Z、6.1.Z。

Ruby on Rails のメンテナンスポリシー - Railsガイド

そして以下のようなGitHub Action用のyamlを用意します。

name: CI

on:
  push:
    branches:
      - main
  pull_request:

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        ruby: ["2.7", "3.0", "3.1"]
        gemfile: ["Gemfile", "gemfiles/rails_6_1.gemfile"]
    env:
      BUNDLE_GEMFILE: ${{ matrix.gemfile }}
    steps:
      - uses: actions/checkout@v2
      - uses: ruby/setup-ruby@v1
        with:
          ruby-version: ${{ matrix.ruby }}
      - name: install dependencies
        run: bundle install --jobs 3 --retry 3
      - name: migration
        run: |
          bin/rails db:create RAILS_ENV=test
          bin/rails db:migrate RAILS_ENV=test
      - name: test
        run: bin/rails test

ポイントは以下のmatrixでrubyとgemfileを指定して、BUNDLE_GEMFILEmatrix.gemfileを指定することで動的に読み込むgemfileを変更しているところです。

    strategy:
      matrix:
        ruby: ["2.7", "3.0", "3.1"]
        gemfile: ["Gemfile", "gemfiles/rails_6_1.gemfile"]
    env:
      BUNDLE_GEMFILE: ${{ matrix.gemfile }}

gemfile (BUNDLE_GEMFILE): The name of the file that bundler should use as the Gemfile. This location of this file also sets the root of the project, which is used to resolve relative paths in the Gemfile, among other things. By default, bundler will search up from the current working directory until it finds a Gemfile. https://bundler.io/man/bundle-config.1.html#LIST-OF-AVAILABLE-KEYS

これで以下のような感じでRubyRailsのバージョンのマトリクスで実行することができます。

f:id:madogiwa0124:20220122224944p:plain

参考

sinsoku.hatenablog.com

sue445.hatenablog.com