Getting started with PHP tests

Local Development

If Starting from scratch

  1. Download a zip from the cno-starter-theme or start a new Github repo with that as the template.
  2. Migrate all files to a fresh Local WP site (including the .git folder if it exists)
  3. Follow the readme to get the theme started.

If starting on an existing repo

  1. Create a bin folder inside the theme folder and add 2 files: install-wp-tests.sh and local-mysql-socket.sh
  2. Copy the contents from the Github Template Theme repo
  3. Update composer.json to include the following key/value pairs:
    • autoload-dev
    • scripts.test and scripts.install-tests
    • Update the path to be your theme name (from cno-starter-theme to your-theme-name)
    • require-dev: add the missing packages (phpunit & yoast/phpunit-polyfills
  4. Run composer update -w to update/install new dependencies
  5. Add .wp-tests to your .gitignore
# .gitignore
# ...rest of .gitignore...

# Tests
.wp-tests/

Enabling Code Coverage

  1. In Local, click on Site Folder, then navigate to conf/php/php.ini.hbs.
  2. Open the file with TextEditor (VS Code autoformat can royally screw things up) and find the following:
# conf/php/php.ini.hbs

{{#if xdebugEnabled}}
xdebug.mode=debug,develop
  1. Add ‘coverage’ as the third item in the list
# conf/php/php.ini.hbs

{{#if xdebugEnabled}}
xdebug.mode=debug,develop,coverage
  1. Add the resulting new files to `.gitignore
# .gitignore 
# ...rest of .gitignore...

# Tests
.wp-tests/
.phpunit.result.cache
.phpunit.cache
html-coverage/

Init Test Suite Locally

  1. Click the Site Shell button on a local WP site
  2. Run wp scaffold theme-tests [theme-name]
    • When you see Warning: file already exists, skip the file
    • Delete / move the .circle-ci folder, .phpcs.xml.dist file, and phpunit.xml.dist (if you need the phpunit xml, copy it from the template repo and place it in the root of the repo (/public). Be sure to update the theme name if doing so!
  3. Run composer install-tests
  4. Run composer test

Weirdness

  • PHPUnit must run version ^9 until things get updated (which you can track here)—even though PHPUnit is on v12 (at time of writing).
  • The final lines of install-wp-tests.sh symlink the WordPress tests directory so PHP intelephense knows about the test classes (no more red squigglies). You should see a .wp-tests/wordpress-tests-lib folder with /data, /includes, a wp-tests-config.php file and a wp-tests-config.php.bak file.
    • If you see these and see red squigglies, reload the window (VS Code Command Palette (Cmd + Shift + P) then "Developer: Reload Window")

See something inaccurate?