Pest helpers for creating models using factories

By @samuel · 2021-08-30 13:04

Pest helpers for creating models using factories

One thing I dislike about factories is that they make tests a bit too messy:

test('orders can be accepted', function () {
    /** @var Order $order */
    $order = Order::factory()->create(['status' => 'received']);

    $order->accept();

    expect($order->status)->toBe('accepted');
});

So a pattern I like to use is creating global helpers for each model I'm using in tests:

// Pest.php file
function order(array $attributes = []): Order
{
    return Order::factory()->create($attributes);
}

The function is short and has a return typehint, which makes tests a lot cleaner:

test('orders can be accepted', function () {
    $order = order(['status' => 'received']);

    $order->accept();

    expect($order->status)->toBe('accepted');
});

It especially pairs well with pest, where everything is a lowercase global helper already.

Oh and if you'd be interested, I can share the full code that I use when I want to support named arguments as well:

$order = order(status: 'received');