Class-Based Factories with Laravel Poser

Packages

April 10th, 2020

factory-smoking-featured.png

With Laravel Poser, you can “create class-based model factories in Laravel applications in seconds.” This package works by creating factory classes by hand or using the artisan make:poser command:

1namespace Tests\Factories;
2 
3use Lukeraymonddowning\Poser\Factory;
4 
5class UserFactory extends Factory {}

Here’s a basic example of a test case using a Poser factory class:

1/** @test */
2public function a_user_can_have_customers()
3{
4 UserFactory::times(20)
5 ->hasAddress()
6 ->withCustomers(CustomerFactory::times(20)->withBooks(5))();
7 
8 $this->assertCount(20 * 20 * 5, Book::all());
9}

Poser is smart enough to figure out that withCustomers() is a reference to a CustomerFactory class, so you could write it as follows instead:

1/** @test */
2public function user_has_customers()
3{
4 $user = UserFactory::new()
5 ->withCustomers(30)
6 ->create();
7 
8 $this->assertCount(30, $user->customers);
9}

Another highlight is the ability to encapsulate everyday factory tasks:

1class CompanyFactory extends Factory
2{
3 public function withMainUser()
4 {
5 return $this->afterCreating(function(Company $company) {
6 $company->setMainUser(
7 UserFactory::new()
8 ->forCompany($company)->create()
9 );
10 });
11 }
12}

The poser readme has many thorough examples and details about how to use this package. You can learn more by checking out Poser on GitHub!

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.