Fiton012's avatar

Model factory increment value and reset for each test

I have my ProductFactory as below:

class ProductFactory extends Factory
{

    protected $model = Product::class;

    public function definition(): array
    {
        static $order_column = 1;
        return [
            'title' => $this->faker->sentence,
            'order_column' => $order_column++,
        ];
    }

}

This works as it increments the order_column upon creation of two or more tests. However, I want this static variable to be reset for each of my test function ie.

public function testCanCreateProductsOfStatusDraft() {
	Prouct::factory()->count(2);
}
 // This will create
[
	[
	'id' => 1,
	'title' => 'product1',
	'order_column' = 1
	],
	[
	'id' => 2,
	'title' => 'product2',
	'order_column' = 2
	],
]



public function testCanCreateProductsOfStatusComplete() {
	Product::factory()->count(2);
}
 // This will create
[
	[
	'id' => 1,
	'title' => 'product1',
	'order_column' = 3  => I want this to be 1
	],
	[
	'id' => 2,
	'title' => 'product2',
	'order_column' = 4  => I want this to be 2
	],
]
0 likes
1 reply
martinbean's avatar
Level 80

@spyralex Then don’t make it static.

This logic should already been in your model any way, otherwise you’re going to have order number sequence logic in both your actual model and your tests.

1 like

Please or to participate in this conversation.