thephpleague / factory-muffin

Enables the rapid creation of objects for testing
https://factory-muffin.thephpleague.com/
MIT License
531 stars 72 forks source link

Include autoincrement number for (better) UUID support #382

Closed simplenotezy closed 8 years ago

simplenotezy commented 9 years ago

When defining a muffin, I'd like to be able to define a value that is auto incremented. For instance; I make use of UUID, and when writing tests, it could be very useful to be able to call users like this: 1, 2, 3,4.

I.e:

FactoryMuffin::define(
    'User', [
        'id'                        => 'autoincrement', // would produce: 1, 2, 3, 4, 5, etc for each muffin
        'firstname'     => 'string',
        'lastname'          => 'string',
        'email'             => 'email',
        'size_system'       => 'numberBetween|1;7',
    ]
);

Is this possible as of right now?

scottrobertson commented 9 years ago

@GrahamCampbell FactoryGirl has an idea of Sequences, it's maybe something we can implement:

FactoryGirl.define do
  factory :user do
    sequence(:email) { |n| "user#{n}@example.com"}
  end
end
FactoryGirl.define do
  factory :user do
    sequence(:id)
  end
end

Quick idea:

$fm->define('User')->setDefinitions([
  'email' => $fm->sequence(function($n) {
    return "user{$n}@example.com";
  })
]);
$fm->define('User')->setDefinitions([
  'id' => $fm->sequence()
]);

The only issue with that implementation is that the sequence is global, and not per factory.

scottrobertson commented 9 years ago

@canfiax as a work around, you could use a combination of fakers unique() and randomDigitNotNull()

GrahamCampbell commented 8 years ago

This is already possible using our callable generator.

GrahamCampbell commented 8 years ago

Just pass in something like this:

function () use ($gen) {
    $gen->next();
};

Where the $gen variable is an instance of a class that looks like this:

class Gen
{
    private $last = 0;

    public function next()
    {
        return ++$this->last;
    }
}
GrahamCampbell commented 8 years ago

Or, even just this:

function () {
    static $last;

    if ($last === null) {
        return $last = 1;
    }

    return ++$last;
};
sharan1 commented 4 years ago

@GrahamCampbell when we updated factory muffin from v2.1 to v3.1

For auto-incrementing ids, we used to use the following function:

function () {
        static $last;
         if ($last === null) {
             return $last = 1;
         }
         return ++$last;
}

But after upgrading the same function always started returning 1, resulting in errors for duplication of primary key in our test database.

Any idea what could be the issue and how to resolve it?