快速整合 Laravel 與 Github Actions

前言

Github Action 是 Github 提供的 CI/CD 的服務,讓你可以透過自動化的方式進行打包、測試、部署專案程式碼。

以下是簡單的紀錄該如何整合 Laravel 與 Github Actions

設定方式

  1. 先在 Github 建立全新的 Laravel 專案
  2. Github 會自動依據專案內容提供建議的 actions

github-action

按下 Github 建議的 Laravel action後出現的畫面,右方也會建議其他的 Actions

github-action

主要的 laravel.yml 內容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
name: Laravel

on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
laravel-tests:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Copy .env
run: php -r "file_exists('.env') || copy('.env.example', '.env');"
- name: Install Dependencies
run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist
- name: Generate key
run: php artisan key:generate
- name: Directory Permissions
run: chmod -R 777 storage bootstrap/cache
- name: Create Database
run: |
mkdir -p database
touch database/database.sqlite
- name: Execute tests (Unit and Feature tests) via PHPUnit
env:
DB_CONNECTION: sqlite
DB_DATABASE: database/database.sqlite
run: vendor/bin/phpunit

另外如果在測試過程中需要 MySQL 的環境,Github Actions 也支援以 Docker 的方式建立環境,只要在 jobs 中加入 services

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
name: Laravel

on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
laravel-tests:
runs-on: ubuntu-latest
services:
mysql-service:
# Docker Hub image (also with version)
image: mysql:8.0
env:
MYSQL_ALLOW_EMPTY_PASSWORD: yes
MYSQL_DATABASE: db_test
ports:
- 3306
# Set health checks to wait until mysql database has started (it takes some seconds to start)
options: >-
--health-cmd="mysqladmin ping"
--health-interval=10s
--health-timeout=5s
--health-retries=3
steps:
- uses: actions/checkout@v2
- name: Copy .env
run: php -r "file_exists('.env') || copy('.env.example', '.env');"
- name: Install Dependencies
run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist
- name: Generate key
run: php artisan key:generate
- name: Directory Permissions
run: chmod -R 777 storage bootstrap/cache
- name: Execute tests (Unit and Feature tests) via PHPUnit
env:
DB_PORT: 3306
run: vendor/bin/phpunit
  1. Push 程式碼到 Github,開始自動化流程

參考

https://robertodev.medium.com/continuous-integration-with-github-actions-and-laravel-6-e6cb9aa5aea9
https://medium.com/swlh/test-automation-for-laravel-7-and-mysql-with-github-actions-467493c2f7ed
http://www.ruanyifeng.com/blog/2019/09/getting-started-with-github-actions.html
https://github.com/actions/virtual-environments
https://freek.dev/1590-how-to-use-a-mysql-database-on-github-actions