I'm trying to set up testing for a Wordpress child theme. I've use the wp-cli
wp scaffold theme-tests
command to scaffold some tests. Inside of my child theme's functions.php
file, I load some functions from the parent theme by calling
require_once get_template_directory() . '/lib/init.php';
This works correctly and loads the parent theme's init.php
file when I'm using the theme in the browser. However, when I try to test the theme using phpunit
, get_template_directory()
returns the child theme's path.
I've checked that the parent theme is available and loaded by outputting the following statement just above the code above:
wp_get_theme()->parent()->name
This correctly returns the parent theme's name when using phpunit, which shows that the environment knows about the parent theme and can find it. Am I doing something wrong? Do I need to add something to the scaffolded bootstrap.php
file to make this load correctly when testing?
edit:
Based on Harpreet's answer, I made the following changes in bootstrap.php
. It seems to work for now:
I adding the following into the _register_theme()
function:
add_filter( 'template_directory', 'fix_phpunit_get_template_directory', 10, 3 );
and I added the following function:
function fix_phpunit_get_template_directory( $template_dir, $template, $theme_root ) {
return wp_get_theme()->parent()->get_stylesheet_directory();
}
This happens when you are expecting word press to automatically look for the directory you want what it is not doing.
why is it failing: get_template_directory()
points to the wrong directory in PHPUnit environment.
Fix: Use wp_get_theme()->parent()->get_stylesheet_directory()
to explicitly load the parent theme functions in tests.
WP_PHPUNIT_BOOTSTRAP : you can also use this separate test and user behavior.