The goal of this Package is to enable the rapid creation of objects for the purpose of testing.
It's basically a "factory_girl", simplified for use with PHP.
Via Composer
{
"require": {
"league/factory-muffin": "~2.0@dev"
}
}
To start with, we need to create some defintions.
In this example, we will create them in the /tests/factories/all.php
:
<?php
use League\FactoryMuffin\Facade\FactoryMuffin;
FactoryMuffin::define('Message', array(
'user_id' => 'factory|User',
'subject' => 'sentence',
'message' => 'text',
'phone_number' => 'randomNumber|8',
'created' => 'date|Ymd h:s',
'slug' => 'call|makeSlug|string',
));
FactoryMuffin::define('User', array(
'username' => 'firstNameMale',
'email' => 'email',
'avatar' => 'imageUrl|400;600',
'greeting' => RandomGreeting::get(),
'four' => function() {
return 2 + 2;
},
));
You can then use these factories in your tests:
<?php
use League\FactoryMuffin\Facade\FactoryMuffin;
class TestUserModel extends PHPUnit_Framework_TestCase
{
public static function setupBeforeClass()
{
FactoryMuffin::loadFactories(__DIR__ . '/factories');
FactoryMuffin::setSaveMethod('save'); // this is not required, but allows you to modify the method name
}
public function testSampleFactory()
{
$message = FactoryMuffin::create('Message');
$this->assertInstanceOf('Message', $message);
$this->assertInstanceOf('User', $message->user);
}
public static function tearDownAfterClass()
{
FactoryMuffin::setDeleteMethod('delete'); // this is not required, but allows you to modify the method name
FactoryMuffin::deleteSaved();
}
}
Kind | Option | Description | Example |
---|---|---|---|
factory | model | Will run ->create() on another model and return it's id | factory |
call | method | Allows you to call any static methods | call |
closure | closure | Allows you to call pass a closure that will be called | function {return 1;} |
default | string | Any Kinds that are not reccognised will try and load from Faker, or return the text | creditCardDetails |
If a model cannot be saved to the database, for example if it fails validation through a library like Ardent, a League\FactoryMuffin\Exception\SaveFailedException
will be raised.
$ ./vendor/bin/phpunit
Please see CONTRIBUTING for details.
The MIT License (MIT). Please see License File for more information.