LoginSignup
6

More than 3 years have passed since last update.

GItLab CIでユニットテストを自動実行+カバレッジを出力してGitLab Pagesにホスティングする

Last updated at Posted at 2019-06-25

自前で運用しているGitLab CE(Community Edition)で、Pipelineを利用して
LaravelアプリケーションのPHP Unitを自動で回す設定を作成した時のメモ

PHP Unit設定

PHP Unitを実行した際に、カバレッジのデータがHTMLとして出力されるように、以下の設定を行う

phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
... 省略

+    <logging>
+        <log type="coverage-clover" target="public/coverage/logs/clover.xml"/>
+        <log type="coverage-html" target="public/coverage"/>
+    </logging>
</phpunit>

GitLab CI設定

Gitリポジトリのルート配下に.gitlab-ci.ymlを作成する。

.gitlab-ci.yml
# composerによって生成されるvendor配下をキャッシュする
cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths:
    - vendor/

# Build and Test
php-7.2: &build
  image: php:7.2-cli-alpine
  variables:
    COMPOSER_VERSION: 1.8.6
  script:
    # 必要なライブラリをインストール
    - apk add git autoconf build-base
    - pecl install xdebug
    - docker-php-ext-install mysqli pdo pdo_mysql
    - docker-php-ext-enable xdebug
    - curl https://getcomposer.org/download/${COMPOSER_VERSION}/composer.phar > composer.phar
    - php composer.phar install
    # .envの作成
    - cp .env.example .env
    # ユニットテストの実行
    - vendor/bin/phpunit --configuration phpunit.xml --coverage-text --colors=never
  artifacts:
    paths:
      # 生成したカバレッジレポートを、次のjobで利用する
      - public/coverage

# 異なるPHPのバージョンを指定してジョブを回したい場合、
# 以下のように`build`アンカーを呼び出したうえで、別のalpineのimageを指定すればOK
php-7.1:
  <<: *build
  image: php:7.1-cli-alpine
  # 以下のようにすれば、composerのバージョンを指定できる
  variables:
    COMPOSER_VERSION: 1.6.5

# Unitテストのカバレッジを、Gitlab Pagesにホスティングする
pages:
  stage: deploy
  extends: php-7.2
  artifacts:
    paths:
      - public
  only:
    - develop

これで、GitLabのリモートリポジトリにgit pushすると自動でテストが走る。
以下のURLにアクセスすると、HTML出力したユニットテストのカバレッジが確認できる。
http://{GitLabドメイン}/{プロジェクト名}/coverage/

参考サイト

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