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

hamburghost's avatar

How to mock a user with a Cashier/Stripe subscription?

I'm trying to test things like checking if a user on a specific subscription plan has access to a specific feature and I can't find how to mock a subscription.

$user = factory(\App\User::class)->make([]);

works fine to create a user but then if I try to call $user->newSubscription() it fails because the method doesn't exist (although it's provided by the Billable trait).

One workaround would be to use persisting mocks so the user actually gets saved on the database at which point $user->newSubscription() would be available but then calling it would make a real call to Stripe which is not only slow, it adds a bunch of test data on the Stripe account. Ideally when mocking I'd be able to factory() a user model directly and say "this model is on the monthly plan".

Anyone has an idea? In the Cashier tests it seems to hit Stripe (https://github.com/laravel/cashier/blob/7.0/tests/CashierTest.php) which is probably useful for them but not ideal for an app using Cashier. I'm assuming Cashier is working so I don't want to test that.

Thanks

0 likes
3 replies
hamburghost's avatar
hamburghost
OP
Best Answer
Level 3

Turns out I was probably doing something wrong, but I was able to create a new factory for Cashier's Subscription class:

$factory->define(\Laravel\Cashier\Subscription::class, function(Faker\Generator $faker) {
    static $user_id;
    static $stripe_plan;
    static $name;
    static $stripe_id;

    return [
        'user_id' => $user_id,
        'name' => $name ?: $faker->randomElement(['main']),
        'stripe_id' => $stripe_id,
        'stripe_plan' => $stripe_plan ?: $faker->randomElement(['plan-1', 'plan-2', 'plan-3']),
        'quantity' => 1
    ];
});

Once I have a user created in my test, I grab its ID and create the subscription with factory():

        $plan = factory(Subscription::class)->create([
            'user_id' => $user->id,
            'stripe_plan' => 'plan-1',
            'stripe_id' => $token,
        ]);

Then, $user->subscribed('main', 'plan-1') is true.

Hopefully that helps someone else at some point,

10 likes
TxNuno's avatar

Where are you getting your $token variable from? I am trying to test subscriptions in my app and I hit a wall for several hours now..

3 likes

Please or to participate in this conversation.