Created
September 9, 2020 08:25
-
-
Save fourstacks/9cc6a68ed25fbbf00aa016da34f9a8be to your computer and use it in GitHub Desktop.
Example TestCase using Laravel 8 model factories
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tests; | |
use Illuminate\Database\Eloquent\Factories\Factory; | |
use Illuminate\Foundation\Testing\TestCase as BaseTestCase; | |
use Illuminate\Support\Str; | |
abstract class TestCase extends BaseTestCase | |
{ | |
use CreatesApplication; | |
// Our codebase is structured by domain, so our models live | |
// in nested directories rather than App/Models e.g. | |
// App/Domain/Posts/Models/Post | |
// App/Domain/Posts/Models/Comment | |
public function setUp(): void | |
{ | |
parent::setUp(); | |
Factory::guessFactoryNamesUsing(function (string $modelName) { | |
// We can also customise where our factories live too if we want: | |
$namespace = 'Database\\Factories\\'; | |
// Here we are getting the model name from the class namespace | |
$modelName = Str::afterLast($modelName, '\\'); | |
// Finally we'll build up the full class path where | |
// Laravel will find our model factory | |
return $namespace.$modelName.'Factory'; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment