aaronbullard / factory-biscuit
Quickly create PHP class instances for testing using Faker and Firehose Hydrator.
v1.0.0
2018-11-24 23:34 UTC
Requires
- php: ^7.1
- aaronbullard/firehose: ^1.0
- fzaninotto/faker: ^1.8
Requires (Dev)
- mockery/mockery: ^1.1
- phpunit/phpunit: ^7.3
This package is auto-updated.
Last update: 2024-10-25 13:30:49 UTC
README
Quickly create PHP class instances for testing using Faker and Firehose Hydrator.
Installation
Library
git clone git@github.com:aaronbullard/factory-biscuit.git
Composer
composer require aaronbullard/factory-biscuit
Testing
composer test
Usage
Define your factories
// Factories.php use Faker\Generator; use FactoryBiscuit\Factory; use FactoryBiscuit\Tests\Mocks\Entity\Foo; use FactoryBiscuit\Tests\Mocks\Entity\Bar; $factory->define(Foo::class, function(Generator $faker, Factory $factory){ return [ 'bar' => function() use ($factory){ return $factory->of(Bar::class)->make(); }, 'baz' => $faker->word, 'qux' => $faker->word ]; }); $factory->define(Bar::class, function(Generator $faker, Factory $factory){ return [ 'bar' => $faker->word ]; });
Load your factory file
use FactoryBiscuit\Factory; $factory = new Factory(); $factory->load(__DIR__ . '/Factories.php');
Examples
Create an instance
$foo = $factory->of(Foo::class)->make(); $this->assertInstanceOf(Foo::class, $foo);
Create multiple instances
$foos = $factory->of(Foo::class)->times(3)->make(); $this->assertInstanceOf(Foo::class, $foos[0]); $this->assertCount(3, $foos);
Override attributes of an instance
$foo = $factory->of(Foo::class)->make([ 'baz' => 'newBaz' ]); $this->assertEquals('newBaz', $foo->baz());
Create a specially defined instance type
// Create a factory of class Foo with settings of 'colors' $factory->defineAs(Foo::class, 'colors', function($faker, $factory){ return [ 'bar' => 'red', 'baz' => 'green', 'qux' => 'blue' ]; }); $foo = $factory->of(Foo::class, 'colors')->make(); $this->assertInstanceOf(Foo::class, $foo); $this->assertEquals('red', $foo->bar()); $this->assertEquals('green', $foo->baz());
Implement the FactoryBiscuit\ManagerRegistry interface to persist instances upon creation
$factory = new Factory(Faker::create(), $managerRegistry); // call the 'create' method to create a persisted instance $user = $factory->of(User::class)->create(); $this->assertInstanceOf(User::class, $user); $this->assertTrue( DB::table('users')->where('id', '=', $user->id)->exists() );
For more examples, see the tests: tests\FactoryTest.php