dimanche 29 mars 2020

Fake an Observer for Testing?

I'm building a Test to test that a monthly subscription can be made through an api endpoint. I have a subscription observer that assigns the user a role based on their subscription when a new subscription is created, and this is giving me some trouble with testing.

I have a SubscriptionObserver which has the following:

/**
 * Handle the subscription "created" event.
 *
 * @param  \App\Subscription  $subscription
 * @return void
 */
public function created(Subscription $subscription)
{
    ($subscription->stripe_plan == 'monthly') ? auth()->user()->assignRole('basic-user') : auth()->user()->assignRole('premium-user');
}

My test is:

/** @test */
public function it_can_create_a_monthly_subscription()
{

    $data = [
      'plan' => 'monthly',
      'payment' => 'pm_card_visa',
    ];

    $response = $this->actingAs($this->unsubscribedUser, 'api')->post('api/subscriptions', $data);


    $response
    ->assertSuccessful()
    ->assertJsonStructure([
      "subscription_created",
      "subscription" => [
          "name",
          "stripe_id",
          "stripe_status",
          "stripe_plan",
          "quantity"
      ]
    ]);

}

The error i'm getting is:

1) Tests\Feature\SubscriptionTest::it_can_create_a_monthly_subscription
Error: Call to a member function assignRole() on null

Any suggestions on how I can resolve this?

Aucun commentaire:

Enregistrer un commentaire