0

This is primarily for the sake of setting data up during testing; it appears that there is no official way in the documentation to get factories working as they do in the base Laravel Framework. How can I instantiate them so that I could, for example, instantiate a set of models before running a test?

Dakota Trotter
  • 310
  • 4
  • 8
  • Couldn't find anything on this anywhere, save for a few forums posts of people asking how to do it (with no reply), so after figuring it out, I thought I should share it. – Dakota Trotter Sep 13 '19 at 16:20

2 Answers2

2

In your base test file in the setUp method (or in your ServiceProvider if you need access to them outside of testing), you'll want to attach the the Eloquent Factory as a singleton to the container, which takes the Faker Generator and the path to the factory directory as arguments.

$this->app->singleton(Illuminate\Database\Eloquent\Factory::class, function($app) {
    $faker = $app->make(Faker\Generator::class);
    return Illuminate\Database\Eloquent\Factory::construct($faker, __DIR__.('/../path/to/factories/dir'));
});
Dakota Trotter
  • 310
  • 4
  • 8
1

Here is also a snippet to add your factories in the plugin: https://octoberduck.com/ru/article/factories-in-a-plugin

Place this code in your Plugin.php:

use Illuminate\Database\Eloquent\Factory as EloquentFactory;

public function register()
{
    app(EloquentFactory::class)->load(plugins_path('author/plugin/factories'));
}
Vdomah
  • 46
  • 1
  • 4