Checking to see if user has subscriptions causes test to fail unexpectedly [Laravel Cashier]
I've created a method that processes user checkouts using cashier:
CheckoutController.php (working)
public function processCheckout(Request $request)
{
$plan = Plan::findOrFail($request->billing_plan_id);
try {
$user = auth()->user()->newSubscription($plan->name, $plan->stripe_plan_id)->create($request->payment_method['id']);
return response([], 201);
} catch (\Exception $e) {
return response([], 500);
}
}
SubscriptionsTest
use RefreshDatabase;
protected $monthlyPlan;
protected $yearlyPlan;
protected function setUp(): void
{
parent::setUp();
$this->monthlyPlan = factory('App\Plan')->create(['name' => 'Monthly', 'stripe_plan_id' => 'plan_thing']);
$this->yearlyPlan = factory('App\Plan')->create(['name' => 'Yearly', 'stripe_plan_id' => 'plan_thing2']);
}
/** @test */
public function a_user_can_subscribe_to_a_plan()
{
$this->withoutExceptionHandling();
$this->actingAs($user = factory('App\User')->create());
\Stripe\Stripe::setApiKey(\Config::get('services.stripe.secret'));
$payment_method = \Stripe\PaymentMethod::create([
'type' => 'card',
'card' => [
'number' => '4242424242424242',
'exp_month' => 5,
'exp_year' => 2021,
'cvc' => '314',
],
]);
$response = $this->json('POST', '/api/checkout', ['billing_plan_id'=> 1, 'payment_method' => $payment_method ] )
->assertStatus(201);
$this->assertTrue($user->subscribed('Monthly'));
}
Everything works great until I need to check to see if a user is already subscribed, and if they aren't create a subscription auth()->user()->newSubscription(). This is to prevent duplicate subscriptions.
CheckoutController (Not working)
public function processCheckout(Request $request)
{
try {
$plan = Plan::findOrFail($request->billing_plan_id);
$user = $user = auth()->user();
//If user has no subscriptions subscribe them to new plan
if($user->subscriptions->count() === 0){
$user->newSubscription($plan->name, $plan->stripe_plan_id)->create($request->payment_method['id']);
//dd($user->subscribed('Monthly'));
return response([], 201);
}
} catch (\Exception $e) {
return response([], 500);
}
}
Test:
Tests\Feature\SubscriptionsPlansTest::a_user_can_subscribe_to_a_plan Failed asserting that false is true.
As you can see I've //dd($user->subscribed('Monthly')); in the controller method. This returns false. dd($user->subscriptions->toArray()); also returns an empty array.
I'm unsure what is going on here and why dd($user->subscribed('Monthly')); is returning false. I'm pretty sure this works because the front end is working. What's going on?
Please or to participate in this conversation.