While upgrading the new screeenly.com to Laravel 8, I hit a bit of a wall. At first, it wasn’t clear to me how I can get my previous setup of database factories to work with the new and improved Factory Classes.
See, in screeenly I’m using laravel/cashier-paddle. Cashier comes with 3 models: Customer
, Subscription
and Receipt
. In my Laravel 7 testsuite, I’ve created factories for all of them with different states. subscribed
, onTrial
, trialExpired
.
To make writing test easier, I’ve put those states on the User
Factory. Here’s how the code look liked for the subscribed
state.
$factory->afterCreating(User::class, function ($user, $faker) {
$user->customer()->create();
});
$factory->afterCreatingState(User::class, 'subscribed', function ($user) {
$customer = $user->customer()->update([
'trial_ends_at' => null,
]);
factory(Subscription::class)->states(['status_active'])->create([
'billable_id' => $user->id,
'paddle_plan' => app(TestPlan::class)->paddleId()
]);
factory(Receipt::class)->create([
'billable_id' => $user->id,
]);
});
#databases #laravel