Giter VIP home page Giter VIP logo

factory-muffin's Introduction

Factory Muffin 3.3

StyleCI Status Build Status Software License Latest Version Total Downloads

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.

Installing

PHP 5.4+ and Composer are required.

In your composer.json, simply add "league/factory-muffin": "^3.3" to your "require-dev" section:

{
    "require-dev": {
        "league/factory-muffin": "^3.3"
    }
}

Faker support is provided by Factory Muffin Faker. If you want to enable faker support, then you need to add "league/factory-muffin-faker": "^2.3" too:

{
    "require-dev": {
        "league/factory-muffin": "^3.3",
        "league/factory-muffin-faker": "^2.3"
    }
}

Upgrading

It maybe be useful for existing users to check out the upgrade guide.

Usage

Introduction

This is the usage guide for Factory Muffin 3.0. Within this guide, you will see "the xyz function can be called". You should assume that these functions should be called on an instance of League\FactoryMuffin\FactoryMuffin; you should keep track of this instance yourself, and you can of course have multiple instances of this class for maximum flexibility. For simplicities sake, many of our examples include a $fm variable. This variable will actually be made available when files are required using the loadFactories function.

Model Definitions

You can define model factories using the define function. You may call it like this: $fm->define('Fully\Qualifed\ModelName')->addDefinitions('foo', 'bar'), where foo is the name of the attribute you want set on your model, and bar describes how you wish to generate the attribute. You may also define multiple attributes at once like this: $fm->define('Fully\Qualifed\ModelName')->setDefinitions('foo', 'bar'). Note that both functions append to the internal attributes definition array rather than replacing it. Please see the generators section for more information on how this works.

You can also define multiple different model definitions for your models. You can do this by prefixing the model class name with your "group" followed by a colon. This results in you defining your model like this: $fm->define('myGroup:Fully\Qualifed\ModelName')->addDefinitions('bar', 'baz'). You don't have to entirely define your model here because we will first look for a definition without the group prefix, then apply your group definition on top of that definition, overriding attribute definitions where required. Note that if you want to use group prefixes, you must also create a definition without the group prefix as well.

We have provided a nifty way for you to do this in your tests. PHPUnit provides a setupBeforeClass function. Within that function you can call $fm->loadFactories(__DIR__ . '/factories');, and it will include all files in the factories folder. Within those PHP files, you can put your definitions (all your code that calls the define function).

The loadFactories function will recurse through all sub-folders of the path you specify when searching for factory files, except for hidden folders (i.e. starting with a .) which will be ignored. It will also throw a League\FactoryMuffin\Exceptions\DirectoryNotFoundException exception if the factories directory you specify is not found.

Creation/Instantiation Callbacks

You may optionally specify a callback to be executed on model creation/instantiation using the setCallback function, like this: $fm->define('MyModel')->setCallback(function ($object, $saved) {}). We will pass your model instance as the first parameter to the callback and a boolean as the second parameter. The boolean will be true if the model is being persisted to the database (the create function was used), and false if it's not being persisted (the instance function was used). We're using the isPendingOrSaved function under the hood here. Note that if you specify a callback and use the create function, we will try to save your model to the database both before and after we execute the callback.

Generators

Callable

The callable generator can be used if you want a more custom solution. Whatever you return from your closure, or valid callable, will be set as the attribute. The closure/callable will be called with the same parameters as creation/instantiation callbacks described above: an instance of your model as the first parameter (to give you even more flexibility to modify it as you wish) and a boolean indicating if the model is being persisted to the database. In the following examples, we will go through using a closure, or callable, and then how to use faker to generate attributes.

Example 1

As you can see from this example, the ability to use a closure to generate attributes can be so useful and flexible. Here we use it to generate a slug based on the initially randomly generated 5 word long title.

$fm->define('MyModel')->setDefinitions([
    'title' => Faker::sentence(5),
    'slug' => function ($object, $saved) {
        $slug = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $object->title);
        $slug = strtolower(trim($slug, '-'));
        $slug = preg_replace("/[\/_|+ -]+/", '-', $slug);

        return $slug;
    },
]);
Example 2

This will set the foo attribute to whatever calling MyModel::exampleMethod($object, $saved) returns.

$fm->define('MyModel')->setDefinitions([
    'foo' => 'MyModel::exampleMethod',
]);
Example 3

There is a simple example of setting a few different attributes using our faker wrapper.

use League\FactoryMuffin\Faker\Facade as Faker;

$fm->define('MyModel')->setDefinitions([
    'foo'    => Faker::word(),          // Set the foo attribute to a random word
    'name'   => Faker::firstNameMale(), // Set the name attribute to a random male first name
    'email'  => Faker::email(),         // Set the email attribute to a random email address
    'body'   => Faker::text(),          // Set the body attribute to a random string of text
    'slogan' => Faker::sentence(),      // Set the slogan attribute to a random sentence
]);
Example 4

This will set the age attribute to a random number between 20 and 40.

use League\FactoryMuffin\Faker\Facade as Faker;

$fm->define('MyModel')->setDefinitions([
    'age' => Faker::numberBetween(20, 40),
]);
Example 5

This will set the name attribute to a random female first name. Because we've called the unique method first, the attribute should be unique between all your generated models. Be careful with this if you're generating lots models because we might run out of unique items. Also, note that calling Faker::setLocale('whatever') will reset the internal unique list.

use League\FactoryMuffin\Faker\Facade as Faker;

$fm->define('MyModel')->addDefinition('name', Faker::unique()->firstNameFemale());
Example 6

This will set the profile_pic attribute to a random image url of dimensions 400 by 400. Because we've called the optional method first, not all the generated models will have an image url set; sometimes we will return null.

use League\FactoryMuffin\Faker\Facade as Faker;

$fm->define('MyModel')->addDefinition('profile_pic', Faker::optional()->imageUrl(400, 400));
More

Check out the faker library itself to see all the available methods. There are far too many to cover in the documentation here, and far too many for them to cover in their documentation too. Note that you can fiddle with the underlying faker instance through the public methods on our faker class if you want.

Factory

The factory generator can be useful for setting up relationships between models. The factory generator will return the model id of the model you ask it to generate.

Example 1

When we create a Foo object, we will find that the Bar object will been generated and saved too, and it's id will be assigned to the bar_id attribute of the Foo model.

$fm->define('Foo')->addDefinition('bar_id', 'factory|Bar');

$fm->define('Bar')->addDefinition('baz', Faker::date('Y-m-d'));

Creating And Seeding

The create function will create and save your model, and will also save anything you generate with the Factory generator too. If you want to create multiple instances, check out the seed seed function, which accepts an additional argument at the start which is the number of models to generate in the process. The seed function will effectively be calling the create function over and over.

For example, let's create a user model and associate multiple location and email models to each one. Each email will also have multiple token models.

$user = $fm->create('User');
$profiles = $fm->seed(5, 'Location', ['user_id' => $user->id]);
$emails = $fm->seed(100, 'Email', ['user_id' => $user->id]);

foreach ($emails as $email) {
    $tokens = $fm->seed(50, 'Token', ['email_id' => $email->id]);
}

You may encounter the following exceptions:

  • League\FactoryMuffin\Exceptions\ModelNotFoundException will be thrown if the model class defined is not found.
  • League\FactoryMuffin\Exceptions\DefinitionNotFoundException will be thrown if you try to create a model and you haven't defined a model definition for it earlier.
  • League\FactoryMuffin\Exceptions\SaveFailedException will be thrown if the save function on your model returns false.
  • League\FactoryMuffin\Exceptions\SaveMethodNotFoundException will be thrown if the save function on your model does not exist.
  • Any other exception thrown by your model while trying to create or save it.

There are 5 other helper functions available:

  • You may call pending to return an array of all the objects waiting to be saved.
  • You may call isPending with an instance of a model to check if will be saved.
  • You may call saved to return an array of all the saved objects.
  • You may call isSaved with an instance of a model to check if it's saved.
  • You may call isPendingOrSaved with an instance of a model to check if it will be saved, or is already saved.

Also, a reminder that the instance function is still available if you don't want database persistence.

Deleting

You can delete all your saved models with the deleteSaved function. Please note that your saved models will be deleted in the reverse order they were saved to ensure relationships behave correctly.

If one or more models cannot be deleted, a League\FactoryMuffin\Exceptions\DeletingFailedException will be raised after we have attempted to delete all the saved models. You may access each underlying exception, in the order they were thrown during the whole process, with the getExceptions function which will return an array of exceptions. You may encounter the following exceptions:

  • League\FactoryMuffin\Exceptions\DeleteFailedException will be thrown if the delete function on your model returns false.
  • League\FactoryMuffin\Exceptions\DeleteMethodNotFoundException will be thrown if the delete function on your model does not exist.
  • Any other exception thrown by your model while trying to delete it.

It's recommended that you call the deleteSaved function from PHPUnit's tearDownAfterClass function, however, if you are writing tests using Laravel's TestCase, you should call the deleteSaved function from the tearDown method before calling parent::tearDown. This method flushes the application instance's bindings and Factory Muffin would not unable to execute its deletes. Further more, this unbinds the assigned exception handler and you will not be able to troubleshoot your tests due to binding resolution exceptions obfuscating the true exceptions.

Real Examples

To start with, we need to create some definitions:

# tests/factories/all.php

use League\FactoryMuffin\Faker\Facade as Faker;

$fm->define('Message')->setDefinitions([
    'user_id'      => 'factory|User',
    'subject'      => Faker::sentence(),
    'message'      => Faker::text(),
    'phone_number' => Faker::randomNumber(8),
    'created'      => Faker::date('Ymd h:s'),
    'slug'         => 'Message::makeSlug',
])->setCallback(function ($object, $saved) {
    // we're taking advantage of the callback functionality here
    $object->message .= '!';
});

$fm->define('User')->setDefinitions([
    'username' => Faker::firstNameMale(),
    'email'    => Faker::email(),
    'avatar'   => Faker::imageUrl(400, 600),
    'greeting' => 'RandomGreeting::get',
    'four'     => function() {
        return 2 + 2;
    },
]);

You can then use these factories in your tests:

# tests/TestUserModel.php

use League\FactoryMuffin\Faker\Facade as Faker;

class TestUserModel extends PHPUnit_Framework_TestCase
{
    protected static $fm;

    public static function setupBeforeClass()
    {
        // create a new factory muffin instance
        static::$fm = new FactoryMuffin();

        // you can customize the save/delete methods
        // new FactoryMuffin(new ModelStore('save', 'delete'));

        // load your model definitions
        static::$fm->loadFactories(__DIR__.'/factories');

        // you can optionally set the faker locale
        Faker::setLocale('en_EN');
    }

    public function testSampleFactory()
    {
        $message = static::$fm->create('Message');
        $this->assertInstanceOf('Message', $message);
        $this->assertInstanceOf('User', $message->user);
    }

    public static function tearDownAfterClass()
    {
        static::$fm->deleteSaved();
    }
}

Further Information

If you want more information, the following resources are available to you:

Integrations

Contributing

Please check out our contribution guidelines for details.

Credits

Factory Muffin is based on Zizaco Zizuini's original work on "Factory Muff", and is currently maintained by Graham Campbell. Scott Robertson was also a co-maintainer before the 3.0 release. Thank you to all our wonderful contributors too.

Security

If you discover a security vulnerability within this package, please send an email to Graham Campbell at [email protected]. All security vulnerabilities will be promptly addressed. You may view our full security policy here.

License

Factory Muffin is licensed under The MIT License (MIT).

For Enterprise

Available as part of the Tidelift Subscription

The maintainers of league/factory-muffin and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

factory-muffin's People

Contributors

alexpts avatar benharold avatar davertmik avatar deancsmith avatar dimrsilva avatar grahamcampbell avatar hexnet avatar jadb avatar jcldavid avatar jonob avatar jsyi avatar lostkobrakai avatar ls-michielrensen avatar luiz-brandao avatar masonm avatar mbicknese avatar outrunthewolf avatar pete-otaqui avatar philsturgeon avatar pmccarren avatar potherca avatar scottrobertson avatar spencerdeinum avatar theaxel avatar zizaco avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

factory-muffin's Issues

Skeleton

Get any missing files in from the Skeleton package and improve the README to match.

License was already MIT so you can add a LICENSE file with MIT contents, like in the skeleton without any troubles there.

Using FactoryMuff results in Eloquent not found

<?php

use Zizaco\FactoryMuff\FactoryMuff;

class SurveysControllerTest extends TestCase {

    public function __construct()
    {
        // Prepare FactoryMuff
        $this->factory = new FactoryMuff;

        $user = $this->factory->create( 'User' );
        $this->be( $user );
    }

Results in

Fatal error: Class 'Eloquent' not found in /Users/Andreas/Desktop/Reteam/mind16/app/models/Company.php on line 3

<?php

class Company extends Eloquent {

Getting undefined method loadFactories()

When following the "usage" example I'm getting Fatal error: Call to undefined method League\FactoryMuffin\Facade\FactoryMuffin::loadFactories() when trying to call FactoryMuffin::loadFactories(__DIR__ . '/factories');

I've followed the installation instructions exactly but can't figure out why it's not able to find that method.

If I skip loading factories it throws a "Factory not defined" error, so the FactoryMuffin class is clearly being loaded, it just can't find loadFactories() or setSaveMethod().

Using ~2.0@dev.

Integers beginning with 0

Sometime Faker generates numbers that begin with a 0. When we type cast these to an integer they will drop the 0 from the start. This obviously means that the integer is not the same length as what was asked for.

I am not sure how we could handle this. Leaving the type cast a string and returning does not seem like a solution as we are explicitly asking for an integer.

Offical Website

Who wants the job of making the documentation for the website?

Instructions here

RC2 Release Discussion

I think we're nearly ready to tag v1.0.0-RC2. There's just thing I'd like to discuss. I don't like how we're exposing the saved flag in the public api. It would be better if we could handle this internally, with non-public methods where possible.

Seed

Add a "seed" method that allows us to create a number of factories at once. For example:

FactoryMuffim::seed('User', 20);

This will create 20 User objects, save them to the DB and return them.

A third param would allow for overwriting data like our create method does now.

Better error messages?

Hey,

I'm using FactoryMuff combined with Ardent. I've been having some problems with object creation. I think that "Could not save the model of type" message is not informative enough and it would be great if you could be able to display some additional info about the error. In my case, validation was failing for some reason, and since I'm using Ardent, I'd need to do sth like myObject->errors(), but FactoryMuff is just returning this message and I cannot access the object itself.

A potential solution for this could be to return the object (which is created, or not if validation fails) inside of SaveException object. In that way I could do something like:

catch (Exception $e) {
$e->getObject()->getErrors();
}

And see the errors right away.

Thanks!

Create vs. instance

The various tutorials that I have read generally have sample code that looks something like this:

/**
 * Test Post saves correctly
 */
public function testPostSavesCorrectly()
{
  // Create a new Post
  $post = FactoryMuff::create('Post');

  // Save the Post
  $this->assertTrue($post->save());
}

However, create already saves to the database. If you have any unique columns then the assert will fail as the unique constraint will now fail. The more correct usage would be:

/**
 * Test Post saves correctly
 */
public function testPostSavesCorrectly()
{
  // Create a new Post
  $post = FactoryMuff::instance('Post');

  // Save the Post
  $this->assertTrue($post->save());
}

I don't know what you can do about this but I just spent quite a while tracking down why the assert failed and the documentation was not clear at all.

Next stable release

The project hasn't been updated in a while, but still there are a few old commits not in the latest stable release. Are you planning on tagging a new one?

Wiki?

Should the wiki be disabled?

Model::create

I was attempting to override the create method on my model to handle automatic creation of some data on a relationship and noticed that FM does not use the model's create method, but just sets attributes and calls save. Is there a way to call the create method on a model?

Super Race Condition Party

There are two (so far) issues with unit tests failing sporadically, based on silly shit like a second rolling over between date 1 and date 2 objects being made:

➜  factory-muff git:(master) ✗ phpunit
PHPUnit 4.1.0 by Sebastian Bergmann.

Configuration read from /Users/phil/src/factory-muff/phpunit.xml

.SS........F......

Time: 182 ms, Memory: 6.25Mb

There was 1 failure:

1) FactoryMuffTest::test_should_make_simple_calls
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'2014-08-13 12:07:57'
+'2014-08-13 12:07:56'

/Users/phil/src/factory-muff/tests/FactoryMuffTest.php:136

FAILURES!                                          
Tests: 18, Assertions: 25, Failures: 1, Skipped: 2.
Tests: 18, Assertions: 25, Skipped: 2.      
➜  factory-muff git:(master) ✗ phpunit
PHPUnit 4.1.0 by Sebastian Bergmann.

Configuration read from /Users/phil/src/factory-muff/phpunit.xml

.SS...............

Time: 157 ms, Memory: 6.25Mb

OK, but incomplete, skipped, or risky tests!
Tests: 18, Assertions: 25, Skipped: 2.      
➜  factory-muff git:(master) ✗ phpunit
PHPUnit 4.1.0 by Sebastian Bergmann.

Configuration read from /Users/phil/src/factory-muff/phpunit.xml

.SSF..............

Time: 151 ms, Memory: 6.25Mb

There was 1 failure:

1) FactoryMuffTest::test_integer
Failed asserting that 8 matches expected 9.

/Users/phil/src/factory-muff/tests/FactoryMuffTest.php:56

FAILURES!                                          
Tests: 18, Assertions: 25, Failures: 1, Skipped: 2.

Here are three runs, with two different failures and one happy version in the middle.

Random e-mail generation and apostrophes

Even though apostrophes are valid for emails, I got an error on one of my tests because I look for an email address on a HTML output, turns out that I applied HTML entities to email adresses so PHPunit looks for co'[email protected] as string but on HTML output is encoded like this :

May be cool to remove apostrophes from email valid characters, may simplify testing.

Thanks guys!

Move exceptions into their own folder

Copied from fork repo written by @scottrobertson.

While we are switching to V2, i would like to clean up how we store Exceptions.

Currently it is src/League/FactoryMuffin/NoDefinedFactoryException.php

I feel like it should be more like src/League/FactoryMuffin/Exception/NoDefinedFactory.php

Passing closure as array value

I was creeping through the Kind class and noticed that there is a test for this

https://github.com/Zizaco/factory-muff/blob/master/tests/FactoryMuffTest.php#L153

However using php you cannot define a function as a key if its declared as a property on the class.

Is there a nice way to use this feature with having to hack around defining the static array?

I was looking at a way to return a random "choice" from an array, just wondering if anyone else thinks this is a good feature and I can PR.

Remove "Kinds"

We could probably get rid of these are there are similar ones in Faker:

  • Name
  • Date
  • Integer
  • String
  • Text

Muff has alternate meanings

I know this is probably an accident, but lets play the "possible problem avoidance game".

Muff is a word that I consider to mean "vagina". It stands for "muffin" I know, but still.

This looks much worse when factory_girl is the original name of the package.

Factory Kind always calls ::create()

We need to discuss what should happen if our original factory is created with ::instance() and then they have supplied a Factory Kind within that Factory. Right now, that factory is created using ::create() which will save it to the DB. This is a bit weird as we are not saving the original Factory, but we are the one inside that.

The issue with not saving it, is that how do we know what ID to return to the original factory.

Is it possible to generate some fake data directly from the validation rules?

When I'm trying to use Ardent together with factory-muff, I have to create two arrays with duplication of many attributes, one for the validation rules, the other for factory types.

is it possible to support generating fake data directly from the validation rules? at least some of the rules, like alpha, alpha-dash, numeric, email etc. together with size limitation?

Default "kind"

I think a good idea for this package would be to let Faker handle any unknown string, instead of just having it go into the DB.

  • address
  • city
  • email
  • randomLetter
  • streetAddress
  • postcode

There are so many things, that trying to make a "Kind" class for each would get a little silly. New versions could add Kind classes for some that need extra options, but this would provide a decent default.

Right now, I have a factory that looks like this:

    /**
     * @var array Rules for FactoryMuff package
     */
    public static $factory = [
        'client_id'   => 'factory|App\Model\Client',
        'name'        => 'string',
        'add1'        => 'string',
        'add2'        => 'string',
        'add3'        => 'string',
        'add4'        => 'string',
        'postcode'    => 'string',
        'country'     => 'string',
    ];

Cannot Call a non-static method statically

ErrorException: Non-static method League\FactoryMuffin\FactoryMuffin::create() should not be called statically.

I am using it like this which worked previously to the League namespace change (ownership change?):

$user = FactoryMuffin::create('User');

This is how it says to use FactoryMuffin in the documentation, and how I previously used it.

Passing arguments to Faker

We need a clean way to pass arguments to Faker methods.

One issue I can think of is that some of the Faker "Formatters" as they call it, are not actual methods. And I seem to remember calling method_exists did not work for some odd reason.

Shall look into this more tonight.

Add docs for FactoryMuffin::define() Facade method

We need to change the documentation to use the method below, instead of defining static variable/method in models. See #93 #92:

<?php
FactoryMuffin::define('User', array(
      'name' => 'string',
      'active' => 'boolean',
      'email' => 'email'
));
class User
{
}

[Proposal] Fix Previous Versioning Mess Up

There is a bit of a mess up with tags earlier on, and they don't follow semver.

I propose we rename a few of the tags:

  • v1.0 => v1.0.0
  • v1.1 => v1.1.0
  • v1.2 => v1.2.0
  • v1.3 => v1.3.0
  • v1.4=> v1.4.0
  • v1.4.1 is fine as is
  • v1.4.2 is fine as is
  • 1.5.0 => v1.5.0
  • 1.5.1beta => v1.5.1
  • 1.5.1beta2 => v1.5.2
  • 1.5.1beta2 => v1.5.1
  • 1.5.2beta => v1.5.3
  • 1.5.2 => v1.5.2
  • 1.6.0-beta => v1.6.0
  • 1.6.1-beta => v1.6.1
  • 1.6.2-beta => v1.6.2
  • 1.6.3-beta => v1.6.3
  • 1.6.4-beta => v1.6.4

Then the next tags we have may look something like this:

  • v2.0.0-beta1
  • v2.0.0-beta2
  • v2.0.0-RC1
  • v2.0.0-RC2
  • v2.0.0
  • v2.0.1
    And so on...

This will require going through packagist and manually deleting every release, then hitting the force update button. I think it would be worth it in order to get correct versioning that's actually compatible with composer.

1.5.2

Hey @Zizaco

Can we get 1.5.2 released. Tested everything from last week and it all works well.

Thanks

exists is set to true on create - when not saved

The property exists is not set on create.

    $address = FactoryMuff::create('Address');
    $this->assertTrue($address->save());

The save would expect a boolean as return. Only this one will fail. Save returns null.

Laravel Model.php will check this value on save.

   // exists is true??? 
   if ($this->exists)
   {
         // No update, because not in the database 
         $saved = $this->performUpdate($query);
    }
    else
    {
         $saved = $this->performInsert($query);
    }

In order to fix this I have to set the exists property to false

    $address->exists = false;

Scrutinizer / Travis

Get code quality checks and unit tests up and running. Travis can be skipped if you feel like letting scrutinizer do all the work as tests here are not exactly advanced.

Remove FactoryMuffin from Models

Copied from fork repo written by @scottrobertson.

@marcqualie brings up a good point that we should not really have the $factory definitions in our Models.

The way FactoryGirl does this is have the factory definitions separately.

For example, we could do:

<?php
FactoryMuffin::factory('User', array(
    'username' => 'string'
));

FactoryMuffin::factory('Message', array(
    'user' => 'factory|User'
));

This would keep the models clean, and remove the need to have testing specific code in production code.

Definitions file

What do you guys thing is the best way to including the definitions file would be?

So we define Factories like this now:

<?php
FactoryMuffin::define('User', array(
      'name' => 'string',
      'active' => 'boolean',
      'email' => 'email'
));

So we need to advise the users on where to store these, and how to include them

Multiple options support in $kind->getOptions()

Is the support for multiple comma-separated options in Kind's getOptions() currently used or intended for future use? For the date kind, the line $format = $this->getOption(0, 'r'); in generate() gives incorrect interpretations of formats that include commas, since everything after the first comma is ignored. So 'date|F j, Y' generates the format 'July 6' instead of the intended 'July 6, 2014'.

password_confirmation fails

When using the following factory:

public static $factory = array(
    'email'                 =>  'email',
    'firstname'             =>  'string',
    'lastname'              =>  'string',
    'password'              =>  'password',
    'password_confirmation' =>  'password',
);

And test:

$user = FactoryMuff::create('User');
$this->assertTrue($user->save());

This fails.
But when I create the User manually:

$user = new User;
$user->email = '[email protected]';
$user->firstname = 'Demo';
$user->lastname = 'User';
$user->password = 'password';
$user->password_confirmation = 'password';

This passes.
Something I'm missing here?

Text Length

I would like to generate a factory based on this rule:

public static $rules = Array('nr_contrato'      => 'required|min:5' );

How can I generate any "string" or "text" type that always respect the minimun length?

/tests/stubs folder

What is the purpose of this folder? Should the file not just be in /tests/factories since it does exactly the same as those files?

Abandoned?

Hello,

Just a quick question. Has this project been abandoned? Would just like to know before I fork it and add some stuff that i would like added (instead of submitting PR's).

Scott

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.