Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fourstacks
Created September 9, 2020 08:25
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save fourstacks/9cc6a68ed25fbbf00aa016da34f9a8be to your computer and use it in GitHub Desktop.
Save fourstacks/9cc6a68ed25fbbf00aa016da34f9a8be to your computer and use it in GitHub Desktop.
Example TestCase using Laravel 8 model factories
<?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