Update: In case you're curious, the env variables are accessible from the unit test. I'm not sure why there's this inconsistency or how to fix this. Any ideas?
Seeing puzzling and inconsistent results with unit test
Method 1: directly call Laravel Cashier's API to create a new subscription
$user->newSubscription(env('STRIPE_SUBSCRIPTION_PRODUCT_NAME'), env('STRIPE_ID_PLAN_1'))->create($paymentMethodId);
$isUserSubscribed = $user->subscribed(env('STRIPE_SUBSCRIPTION_PRODUCT_NAME'));
This returns $isUserSubscribed = TRUE.
Method 2: My unit test makes an API call to my API endpoint at /api/v1/me/payments/createOrUpdateSubscription:
$response = $this->actingAs($user, 'api')->json('PUT', '/api/v1/me/payments/createOrUpdateSubscription', [
'stripePlanId' => env('STRIPE_ID_PLAN_1'),
'paymentMethodId' => $paymentMethodId
]);
The API endpoint does this (which is exactly the same as what method #1 does directly)
$loggedinUser = auth()->user();
$loggedinUser->newSubscription(env('STRIPE_SUBSCRIPTION_PRODUCT_NAME'), $stripePlanId)->create($paymentMethodId);
$isUserSubscribed = $user->subscribed(env('STRIPE_SUBSCRIPTION_PRODUCT_NAME'));
This returns $isUserSubscribed = FALSE.
Whyy??
@connecteev I think your other methods worked because you were creating a model then asserting against it. With the update method, you already had an instance of a model, then applied an update to a related piece of data, then asserted against the original instance without the changes. Using refresh() will reload the model, along with it's relationships (which would include the changes you made via the PUT request)
It's not necessarily any bad practice on your behalf, it's just something to be aware of. You will require to refresh your model from time to time with unit testing to make a test pass. It's one of the reasons why the refresh() method was included within the framework. Alternatively, if you don't want to refresh the model, you could always assert against the database.
Please or to participate in this conversation.