Setting a constant in wp-browser functional tests

Last year, I started learning how to write automated tests for WordPress using wp-browser. Sometimes, I spend hours figuring out why a certain test is not working as expected, playing with functions and even test levels.

One of my last challenges was to set a constant which my Image Source Control plugin checks before enabling support for the WP Bakery page builder. Only if that constant was set would ISC create a specific output, and my functional test could succeed.

Just using define() wouldn’t work. I am not yet at the level where I could explain why.

I played with some code changes in the plugin that I was testing but without success.

Since I didn’t want to hard-code this constant in the underlying test environment, I had to come up with a way to define it dynamically only during my test.

After many tries, googling, and AI chats, I decided to follow ChatGPT’s suggestion to create a mu-plugin on the fly whose only task would be to set the constant.

I am posting the basic code here since I had difficulty finding something similar. Let me know if there is a simpler approach.

The test file now adds the mu-plugin to the _before() function and removes it in _after().

<?php

namespace ISC\Tests\Functional;

class WP_Bakery_Cest {

	/**
	 * Path to the mu plugin
	 *
	 * @var
	 */
	protected $muPluginPath;

	public function _before(\FunctionalTester $I) {
		// create a mu-plugin on the fly that
		// adjust the path depending on where the test files are located
		$this->muPluginPath = codecept_root_dir('../../../wp-content/mu-plugins/mu-plugin-wpbakery.php');
		if ( ! file_exists( $this->muPluginPath ) ) {
			file_put_contents( $this->muPluginPath, '<?php if ( ! defined("WPB_VC_VERSION" ) ) { define( "WPB_VC_VERSION", "7.0.0" ); }' );
		}

		…
	}

	/**
	 * Remove the mu plugin again
	 *
	 * @return void
	 */
	public function _after(\FunctionalTester $I) {
		// delete the mu-plugin after the test
		if ( file_exists( $this->muPluginPath ) ) {
			unlink( $this->muPluginPath );
		}

		…
	}
}
Code language: HTML, XML (xml)