Factoryhag is a project mainly written in PHP, it's free.
like factory_girl, but it's for PHP so it's nowhere near as pretty
This is a cheesy knockoff of the magnificent factory_girl.
Some things I like about factories:
Anyway, check out the real deal if you need more information on factories in general.
Drop it in your app somewhere. I use library
, but folks are probably using
vendor
now? Whatever floats your boat.
Right now, I require_once
a file called tests/factories.php
. It looks a
little something like this:
// util provides a bunch of quick shortcuts to FactoryHag methods.
require_once 'FactoryHag/util.php';
use FactoryHag as Hag; // 'cause I'm too lazy to type FactoryHag
// then define your factories:
Hagdefine('user', array(
'username' => 'test',
'password' => 'secret',
));
So then a test file might look like this:
use FactoryHag as Hag;
class UserTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
Hagflush();
}
public function testUsernameEqualsWhateverItIsSetTo()
{
$user = Hagf('user');
$this->assertEquals('test', $user->username);
}
}
That's a pretty crap test, but hopefully it gets the idea across. A couple things to note:
Hagflush
. In the tearDown
method, I'm calling FactoryHagflush
,
which wipes out any records created by FactoryHag, hopefully getting the
database back to a somewhat more pristine state.Hagf
. This is the method that creates a new record and saves it in
the database. It's short for FactoryHagfactory
, but I like to save
typing.Also, you can override the factory defaults. Here's how that test might look if you did that:
public function testUsernameEqualsWhateverItIsSetTo()
{
$user = Hagf('user', array('username' => 'mclovin'));
$this->assertEquals('mclovin', $user->username);
}
build
or attributes_for
.
FactoryHag creates a record and saves it. I'm sure that will be trivial
to implement, I just haven't needed it yet.