
Automate Laravel testing with GitHub Actions to ensure continuous integration and error-free code
Automating testing in Laravel is a critical step in ensuring your application runs smoothly. Integrating GitHub Actions with Laravel allows you to automatically run tests whenever you push code or create pull requests, reducing the chance of errors slipping through. In this guide, we’ll walk you through setting up GitHub Actions to automate Laravel testing, focusing on unit and feature tests.
Automating Laravel testing offers several benefits:
Before we begin, make sure you have:
test.yml File.github/workflows/test.yml file in your repository. This file will define the steps GitHub Actions will take to run your tests.name: Tests Cases
on:
push:
branches: [main, dev]
pull_request:
branches: [main, dev]
jobs:
tests:
name: Run tests
runs-on: ubuntu-latest
services:
mysql-service:
image: mysql:8.0
env:
MYSQL_ALLOW_EMPTY_PASSWORD: yes
MYSQL_ROOT_PASSWORD: ""
MYSQL_DATABASE: test
ports:
- 3306:3306
options: >-
--health-cmd="mysqladmin ping"
--health-interval=10s
--health-timeout=5s
--health-retries=3
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 8.2
tools: composer:v2
coverage: xdebug
- name: Install Dependencies
run: |
cp .env.example .env
composer install -q --no-ansi --no-interaction --no-scripts --no-suggest --no-progress --prefer-dist
php artisan key:generate
- name: Execute tests (Unit and Feature tests) via PHPUnit
env:
DB_CONNECTION: test_mysql
DB_DATABASE_TEST: test
DB_PORT: 3306
DB_USER: root
DB_PASSWORD: ""
APPLE_PAY_PASSWORD: "password"
run: |
php artisan teston: section of the YAML file defines when the workflow should be triggered. In this case, we’ve configured it to run on pushes and pull requests to the main and dev branches.jobs: section specifies the environment in which your tests will run. The runs-on: ubuntu-latest line tells GitHub to use the latest Ubuntu environment.
Next, the services: section defines a MySQL service that your Laravel application will connect to during testing. The health checks ensure that the database service is ready before running your tests.steps: section details the actions GitHub will take to set up and run your tests. It starts with checking out your repository’s code and setting up PHP with the specified version.
Then, we install the necessary dependencies using Composer, copy the example environment file to .env, and generate an application key.By following this guide, you’ve set up a GitHub Actions workflow to automate testing in your Laravel application. This setup ensures that your code is continuously tested, allowing you to catch issues early and maintain a stable codebase.