Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

simplehacker's avatar

Spark and Testing

Hi all,

I guess I'm a little confused about how I can go about running tests which include Spark subscription actions.

I've got a simple test to see if a Firm can be deleted

/** @test */
    public function owners_can_delete_firm()
    {
        $user = User::factory()->create();

        $firm = Firm::factory()->withSubscription()->ownedBy($user)->create();

        $user->refresh();

        $this->actingAs($user)
            ->deleteJson(route('firms.destroy', $firm))
            ->assertStatus(204);

        $this->assertSoftDeleted('firms', $firm->fresh()->toArray());
    }

The withSubscription() method is as it is on in the Sparks documentation https://spark.laravel.com/docs/1.x/spark-stripe/testing.html

in my FirmObserver I've got that it should cancel the subscription when deleting a firm.

public function deleting(Firm $firm)
    {
        $firm->subscription('Standard')->cancelNow();
    }

But when I'm running my test I get Stripe\Exception\InvalidRequestException: No such subscription: 'mvYxUl5dnw'

Okay so that makes sense, the customer and subscription don't exist on Stripe under Test Data (along with Stripe Test API Keys). I create the customer and subscription plan on Stripe, and assign their id's on to my Firm under stripe_id model in the test. This then worked for the first time, but the second time I ran it it couldn't find the subscription on Stripe again, that's because it has actually been cancelled on Stripe. Now obviously I don't want to create a customer and subscription every time I want to run a test.

How can I mock the cancellation of a subscription? Or in my factory have I got to create the customer and subscription rather than stub it as it says in the Spark docs?

0 likes
1 reply
localheinz's avatar

Why not write a unit test for the FirmObserver?

<?php

declare(strict_types=1);

namespace Tests\Integration;

use App\Listeners;
use App\Models;
use Laravel\Cashier;
use PHPUnit\Framework;

final class FirmObserverTest extends Framework\TestCase
{
    public function testDeletingCancelsSubscription(): void
    {
        $subscription = $this->createMock(Cashier\Subscription::class);

        $subscription
            ->expects(self::once())
            ->method('cancelNow');

        $firm = $this->createMock(Models\Firm::class);

        $firm
            ->expects(self::once())
            ->method('subscription')
            ->with(self::identicalTo('Standard'))
            ->willReturn($subscription);

        $observer = new Listeners\FirmObserver();

        $observer->deleting($firm);
    }
}

Please or to participate in this conversation.