Your first WordPress Codeception “cept” acceptance test

With WordPress Codeception, you can run acceptance tests, called Cept tests, that use the format:

  • [test-name]Cept.php

These tests generally run a browser [like Selenium / Chrome] or a broswer simulator [like PhantomJS]. The tests are written in procedural PHP and are very easy to read and understand. In theory, a non programmer can read a Cept test and understand it. That’s a theory though. I haven’t actually seen a Unicorn. In other words, don’t bother showing Gherkin to a business person. They will not understand why you are forcing them to learn “code”.

However, you as a programmer, should be able to look at the following Gherkin scenario, and see if you can figure out what is being requested here. It is only three lines, and it is actually a single sentance in English. Stare at it until you feel that you compleately understand, in your mind, what is expected to happen:

Can you dig it?
There should be a backend shortcode [first-testable-shortcode] that expands to display "Hello world!" when viewed from the frontend.

This is a typical feature request from a business stakeholder. It is the expected feature that doesn’t exist yet, but we are going to make it exist by developing it with TDD!

Here is a Cept test which tests for a “Hello World” shortcode:

Run the test:

  • bin/codecept run acceptance HelloWorldShortcodeCept.php -vvv --html

The test fails.

Now we should add code to make the test pass:

Run the test again:

  • bin/codecept run acceptance HelloWorldShortcodeCept.php -vvv --html

The test passes!
Now it’s time to re-factor. That is, we modify the code to make it easier to read and understand, but we don’t add or change any functionality.
I’ve added namespaces and re-done the plugin in OOP style. The entire plugin code can be found here on Github.

Conceptually, it’s usally easier to start learning testing by doing acceptance tests. It is driving a browser just like a human does, so there is less to learn because you are already familiar with a browser and how it works. If you have a choice, you should generally create a unit test instead of an acceptance test though. There are several reasons:

  • Acceptance tests are slower than unit tests
  • They are more brittle. That is, they may fail for unpredictable reasons. i.e. uncontrollable network latency

Leave a Reply