testbench factory issues I've created a model and factory with testbench make:model User -f, but when I call User::factory()...:
Error: Class "Database\Factories\Models\UserFactory" not found
Currently I solved it by defining newFactory method on model.
The Models segment in the namespace appears superfluous; where was the Factory class actually created?
@tykus workbench/database/factories/UserFactory.php
@amir5 so the namespace is wrong? How’s the namespace been generated in the factory, and how is the Database namespace mapping in your composer.json?
@tykus The UserFactory namespace is correct(Workbench\Database\Factories), and composer.json:
"Workbench\\Database\\Factories\\": "workbench/database/factories/",
@tykus steps to reproduce:
composer init
composer require --dev "orchestra/testbench"
vendor/bin/testbench workbench:install
testbench make:model Post -mf
Then testbench tinker and:
\Workbench\App\Models\Post::factory()->create()
-> Error Class "Database\Factories\Models\PostFactory" not found.
@tykus I can fix it by defining newFactory
protected static function newFactory()
{
return \Workbench\Database\Factories\PostFactory::new();
}
But it probably should work by default when I'm using orchestral/testbench..
@amir5 agreed that it should work with laravel’s default namespaces; however the Factory class is being resolved it clearly incorrect.
What version of Testbench are you working with?
@amir5 this
protected static function newFactory()
{
return \Workbench\Database\Factories\PostFactory::new();
}
is actually the correct approach since you have a non-standard namespace; the resolver cannot guess the correct namespace for your Factory class.
Setup your TestCase.php like this.
use Illuminate\Database\Eloquent\Factories\Factory;
abstract class TestCase extends \Orchestra\Testbench\TestCase
{
.......
/**
* @return void
*/
protected function setUp(): void
{
parent::setUp();
Factory::guessFactoryNamesUsing(function () {
return 'Workbench\\Database\\Factories\\UserFactory';
});
}
.......
}
works for me
To discover the factories inside your Workbench model, you need to enable them in the testbench.yaml file.
workbench:
start: '/'
install: true
health: false
discovers:
web: false
api: true
factories: true // this is what you need
Please sign in or create an account to participate in this conversation.