CakePHP 4 incorrect test table names created from Fixtures

Leaving this here as I…

Login

Blog History

Leaving this here as I just spent an annoying hour trying to figure out why my tests were failing.

  • CakePHP Version: 4.2.5
  • Platform and Target: Ubuntu 20.04, Apache/2.4.41 (Ubuntu), Mysql 8.0.23-0ubuntu0.20.04.1, PHPUnit 8.5.15

What I was doing

I was running CakePHP 4 tests with vendors/bin/phpunit

What I did before I did what I was doing

I sucessfully created some fixtures with bin/cake bake fixture Menus -r -n 100 and bin/cake bake fixture Help -r -n 100

What happened when I did what I was doing

Error is raised

Possibly related to Cake\Database\Exception\DatabaseException: "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dbnamehere.menus' doesn't exist

How I figured out what was causing the problem

I put a die statement before the tearDown() method in my MenusControllerTest.php so it would die before it cleared the tables and I could see the problem.

From the image below you can tell that the menus table and the help table is being incorrectly set to helps and menuses

What causes it

CakePHP tries to guess the correct table name from the class so in the case of fixtures named with class names of HelpFixture and MenusFixture it will do the following.

<?php

require 'vendor/autoload.php';

use Cake\Utility\Inflector;

echo Inflector::tableize('Help') . "\n";
echo Inflector::tableize('Menus') . "\n"

Output

helps
menuses

The Fix

In your Fixture set a table property and the test table will have the name you specify:

/**
 * MenusFixture
 */
class MenusFixture extends TestFixture
{
    public $table  = "menus";

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.