Skip to content

Instantly share code, notes, and snippets.

@lepikhinb
Last active March 19, 2022 20:06
Show Gist options
  • Save lepikhinb/4856e54b16042ecde2a4c2358a37a787 to your computer and use it in GitHub Desktop.
Save lepikhinb/4856e54b16042ecde2a4c2358a37a787 to your computer and use it in GitHub Desktop.
Laravel 8 Model Factory resolver
<?php
namespace Tests;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use ReflectionClass;
use SplFileInfo;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected function setUp(): void
{
parent::setUp();
$factoryFiles = collect(File::allFiles(database_path('factories')));
Factory::guessFactoryNamesUsing(function ($modelName) use ($factoryFiles) {
return $factoryFiles->map(function (SplFileInfo $splFileInfo) {
return 'Database\\Factories\\' .
str_replace(
'/',
'\\',
Str::between($splFileInfo->getPathName(), database_path('factories/'), '.php')
);
})
->filter(function (string $className) use ($modelName) {
$factory = new $className;
$reflection = new ReflectionClass($className);
$property = $reflection->getProperty('model');
$property->setAccessible(true);
return $property->getValue($factory) === $modelName;
})
->first();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment