Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Testing a WP Plugin

I set up a new plugin using the WP Plugin Boilerplate generator: https://wppb.me

Make sure you have wp-cli installed https://wp-cli.org

curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar 
chmod +x wp-cli.phar 
sudo mv wp-cli.phar /usr/local/bin/wp

1 Make composer file

Make a composer.json file in the root:

{
	"name": "donkey-time/donkey-time",
	"description": "An example WP plugin with tests",
	"type": "wordpress-plugin",
	"config": {
		"preferred-install": "dist"
	},
	"extra": {
		"wordpress-install-dir": "vendor/wordpress/wordpress"
	},
	"require": {
		"php": ">=5.3",
		"composer/installers": "~1.0"
	},
	"require-dev": {
		"roots/wordpress": "* || *",
		"wp-phpunit/wp-phpunit": "* || *",
		"phpunit/phpunit": "^5"
	}
}

2 Install dependencies

Then run composer install to pull in all dependencies.

3 Create WP config file

Run a wp command to create a config file (ensure dbprefix is “wptests_”):

wp --path=vendor/wordpress/wordpress/ config create --dbname=wordpress_test --dbuser=root --dbprefix=wptests_

4 Create test scaffold

First make this file in bin/init.php to update the WP_PLUGIN_DIR

<?php

// Set the plugin dir for WordPress so it thinks that this directory is in the
// plugins directory (in order to get the test scaffold)

if ( ! defined( 'WP_PLUGIN_DIR' ) ) {
	define( 'WP_PLUGIN_DIR', dirname(dirname(__DIR__)) );
}

Run this command to do it quickly:

mkdir -p bin && printf "<?php\n\n# Set the plugin dir for WordPress so it thinks this project is inside the plugins directory\n\nif ( ! defined( 'WP_PLUGIN_DIR' ) ) {\n  define( 'WP_PLUGIN_DIR', dirname(dirname(__DIR__)) );\n}" > bin/init.php

4a Generate test scaffold

Then run this command to generate the plugin-tests scaffold for the plugin:

wp --require=bin/init.php --path=vendor/wordpress/wordpress scaffold plugin-tests donkey-time

5 Install WP tests lib

Then run this command so the test runner has the WP testing library available:

WP_CORE_DIR=vendor/wordpress/wordpress WP_TESTS_DIR=tests/wordpress-tests-lib/ bin/install-wp-tests.sh wordpress_tests root "" localhost latest true

6 Then run the unit tests

Run this command to run the tests: WP_TESTS_DIR=tests/wordpress-tests-lib/ vendor/bin/phpunit

Note it must be phpunit version 5.x to work with WP tests

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.