How To Start Testing Your WordPress Code With the Pest PHP Testing Framework – WP Tavern
We will all agree that WordPress has come a good distance since its starting and that it grew into one thing much more than running a blog software program.
At its core, it’s nonetheless a content material administration system (CMS), however with over 59,000 plugins within the wordpress.org listing, you possibly can customise it to be rather more.
The explanation for its reputation is its low entry barrier for each content material creators and builders. Typically this comes with a value. It’s no secret that WordPress has a nasty status relating to improvement. It has lots of legacy baggage and die-hard guidelines that forestall any backward compatibility breaking change relating to PHP code (Gutenberg is one other story I gained’t get into).
That legacy PHP code is commonly utilized by the builders which are beginning to enter the world of programming, and the problem with that’s they will study some unhealthy programming patterns. That in flip means they are going to reuse the poorly written code, growing the quantity of unhealthy code on the planet.
That is the place WordPress will get its unhealthy status within the developer group.
Breaking the cycle
So how can we break this cycle of unhealthy code? By educating new builders how they need to write good code. One instance of educating new builders (but additionally previous ones which are nonetheless clinging to the ‘WordPress’ approach of doing issues) is by writing tutorials.
One other approach is to encourage them to make use of instruments that may assist them write higher code.
I’m presently concerned within the work which goals to launch the brand new model of the WordPress Coding Standards, a algorithm used for the PHP_CodeSniffer instrument that can let in case your code has some potential points (safety, finest practices, code type).
One other instrument that I’ve lately developed is a package that can assist builders arrange WordPress integration exams that use the Pest testing framework.
Okay, so why do we want this new instrument?
The primary motivation behind creating this bundle is to encourage extra individuals to jot down exams for his or her code, particularly plugin builders.
Quite a lot of builders within the WordPress group go together with the mantra: I can see that it really works as a result of I’ve tried it out in my browser. That’s OK, however there are points with that.
First, it’s time-consuming. Each time you make some change, you have to be sure it really works, but additionally that you just didn’t break something.
Second, individuals make errors. We aren’t foolproof, and code could also be misused in methods you by no means thought doable. You’ll be amazed at how inventive individuals will be when writing code.
Automated exams are fast and may also help you in testing numerous circumstances that can occur once you execute your code.
You check for the meant conduct (pleased path), and in a fast approach, you possibly can add examples of how your code can be utilized in a approach you didn’t intend it for use (sad path).
It additionally safeguards your code from regressions. A code regression is once you unintentionally break one a part of your code by including new code.
The issue with exams arrange thus far
Testing in WordPress isn’t a brand new factor. And it’s not such as you couldn’t arrange exams on your code earlier than. There are superb libraries on the market that can show you how to set all the pieces up like wp-browser.
However the issue is that the setup process is commonly clunky.
You’ll want to arrange a separate database for exams, and you have to run sure scripts, then change information to make all of it work.
Let’s face it, it’s not an easy factor to do, and builders are by nature lazy creatures (that’s why we write code to do issues for us 😄).
The purpose of the wp-pest integration check setup is to remove all that additional work.
The way to set it up
As a way to set it up, your challenge should use Composer. It’s a de-facto normal approach of including packages to your code.
In your terminal sort
composer require dingo-d/wp-pest-integration-test-setup --dev
After you’ve downloaded the bundle and its dependencies you possibly can arrange the theme exams by typing
vendor/bin/wp-pest setup theme
Or, within the case you wish to arrange exams on your plugin, you possibly can write
vendor/bin/wp-pest setup plugin --plugin-slug=your-plugin-slug
Optionally, you possibly can present a --wp-version
parameter, to specify which WordPress model you’d like to check your code on.
Within the background, a WordPress occasion can be downloaded, and an in-memory database can be arrange, together with two examples of exams that you would be able to run.
Then, operating both
vendor/bin/pest --group=unit
or
vendor/bin/pest --group=integration
will run the exams.
The fantastic thing about Pest is that its syntax is developer-friendly. It has amazing documentation and nice syntax. Let’s take a look at a easy instance. Say you’re registering a customized submit sort known as ‘Books’:
<?php
/**
* Plugin Title: Take a look at plugin
* Desctiption: Take a look at plugin
* Model: 1.0.0
* License: MIT
*/
operate test_plugin_register_books_cpt() {
$args = array(
'label' => esc_html__( 'Books', 'test-plugin' ),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'e book' ),
'capability_type' => 'submit',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'helps' => array( 'title', 'editor', 'writer', 'thumbnail', 'excerpt', 'feedback' ),
);
register_post_type( 'e book', $args );
}
add_action( 'init', 'test_plugin_register_books_cpt' );
After operating the setup command that provides an instance, a check known as BooksCptTest.php
would appear like this:
<?php
namespace TestsIntegration;
beforeEach(operate () {
father or mother::setUp();
});
afterEach(operate () {
father or mother::tearDown();
});
check('Books customized submit sort is registered', operate () {
// We will use assertions from PHP_Unit.
$this->assertNotFalse(has_action('init', 'test_plugin_register_books_cpt'));
$registeredPostTypes = get_post_types();
// Or we will use expectations API from Pest.
count on($registeredPostTypes)
->toBeArray()
->toHaveKey('e book');
});
Operating vendor/bin/pest --group=integration
provides us the next output:
Putting in...
Operating as single web site... To run multisite, use -c exams/phpunit/multisite.xml
Not operating ajax exams. To execute these, use --group ajax.
Not operating ms-files exams. To execute these, use --group ms-files.
Not operating external-http exams. To execute these, use --group external-http.
PASS TestsIntegrationBooksCptTest
✓ Books customized submit sort is registered
Exams: 1 handed
Time: 0.14s
Conclusion
And identical to that, you’ve the flexibility to run WordPress integration exams in your theme or plugin. Exams are superb as a result of not solely are they safeguarding us from errors, however additionally they pressure us to jot down clear and testable code. That is very true for plugins which have sophisticated logic or are speaking with third-party APIs.
Writing exams for such a codebase will pressure you to consider what your code structure seems to be like so you possibly can simply write automated exams – to not point out the money and time you’ll save from not having to manually check all the pieces.
When you suppose that is one thing you would possibly profit from, be at liberty to make use of it, and star the repository on GitHub.
Hopefully, this can encourage extra WordPress builders to make use of instruments that can improve their coding expertise.