Level 61
Avoid contacting or querying your database in the __construct() method.
1 like
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello everyone,
I have a problem with testing my main app. Here is a small code of my class in Nova
class Settings
{
/**
* Settings constructor.
*/
public function __construct()
{
$this->registerFields();
}
private function registerFields(): void
{
NovaSettings::addSettingsFields([
Text::make('Google API', 'google_api'),
Select::make('Users')->options($this->getFreelancersOnly())
]);
}
/**
* @return array
*/
private function getFreelancersOnly(): array
{
// this code is working fine from the UI
return User::with('info')->whereHas('info', function ($query) {
$query->where('freelancer', 1);
})->get()->pluck('first_name', 'id')->toArray();
}
}
And I have a lot of test classes (for example this one for testing)
class HelpersTest extends TestCase
{
use WithFaker, RefreshDatabase;
/**
* @test
*/
public function just_test_case(): void
{
self::assertTrue(true);
}
}
The problem is that all tests are failing with the error General error: 1 no such table: users, but If I'm removing all content of getFreelancersOnly method everything is working fine. It looks like my Laravel test cases are loading Nova classes before my Seed class. How can I solve this problem? All my tests are failing now :(
Here is my phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" backupGlobals="false" backupStaticAttributes="false" bootstrap="vendor/autoload.php" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<coverage processUncoveredFiles="true">
<include>
<directory suffix=".php">./app</directory>
</include>
</coverage>
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
<php>
<env name="APP_ENV" value="testing"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="MAIL_DRIVER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="DB_CONNECTION" value="testing"/>
</php>
</phpunit>
Avoid contacting or querying your database in the __construct() method.
Please or to participate in this conversation.