How to use GitHub Actions to run unit tests and code sniffers
This post will demonstrate how to execute PHP Unit tests and run a PHP Code Sniffer using GitHub Actions. This can be a useful mechanism to ensure any code being merged into your codebases main branch is passing all tests and is complying with your set coding standards. A red X will appear on the pull request or beside the commit message if tests are not passing or if your code sniffer found issues. A green tick appears if the tests are passing
Setting up the project
My Project directory structure is illustrated here:
My source code is in the folder called src
.
My tests are in the folder called tests
.
My coding standards for the code sniffer to check for are defined in ruleset.xml (For more information on how to set up code sniffer see this post)
Using Composer to execute tests and the code sniffer
Inside the composer.json
file I have included scripts to execute the tests and run the code sniffer:
"scripts": {
"test": "phpunit --bootstrap vendor/autoload.php",
"sniff": "phpcs --standard=ruleset.xml",
"snifferfix" : "phpcbf --standard=ruleset.xml"
},
This allows me to execute the tests and run the code sniffer using composer test
and composer sniff
These will be used later in the GitHub workflow file.
All of this code can be found in this GitHub repository.
Setting up the GitHub Action Workflow
The next step is to define the GitHub Workflow. To do this, create a folder in your project called .github
and inside this folder create another folder called workflows
.
mkdir .github
cd .github
mdkir workflows
Inside the workflows
directory create a file called ci.yml
.
cd workflows
touch ci.yml
Add the following to this file:
name: CI
on: [push]
jobs:
build-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: php-actions/composer@v5 # or alternative dependency management
- name: run tests
run: composer test
- name: change owner of phpcs
run: sudo chmod 777 ./vendor/bin/phpcs
- name: sniff
run: composer sniff
The above code snippet is what causes the tests and code sniffer to run on GitHub. When code is pushed to a GitHub repository with this workflow present, a virtual machine is spun up and your code is cloned to it. The test and code sniffer scripts are then executed. If any of the tests fail or the code sniffer detects issues, the build test fails.
Once you push your code to GitHub with the workflow file included you will be able to see the result of your tests running under the 'Actions' tab of your GitHub repository (Example here). The tests will run every time code is pushed to your repository.
Adding the status of your workflow to your repository
Now that your workflow is set up, you can add the status of it to the repository by including a link in the format here to your README.md
file:

In my example the URL to include was:

This status badge can be seen by visiting the GitHub repository