In this episode, we dive into how easy it is to mock actions in Laravel, using a real-life-inspired example. We're working with subscriptions, specifically creating a subscription for a user and fetching the relevant plan from an external provider like Stripe.
We kick things off by quickly scaffolding a basic Subscription
model (not a full implementation, just the essentials), and then run a migration to get the database ready. After setting up the relationship between users and subscriptions, we implement our main action: CreateSubscription
. This action's job is to take a Stripe ID, fetch the plan details from Stripe (like the interval: month, year, etc.), and then use that data to create a subscription for a user.
Instead of actually integrating the Stripe API in this example, we make a separate action called FetchPlanFromStripe
, which for now just returns dummy data (imagine it's hitting the API behind the scenes). Next, we write a feature test for our subscription creation. We assert that running the action with some test data creates a subscription as expected, and check the interval attribute.
Here's where mocking comes in: We don't really want to rely on what FetchPlanFromStripe
returns every time, especially for different scenarios like monthly or yearly plans. So we use Laravel Actions' built-in mocking abilities to easily control what that action returns in our test. This means we can confidently test our subscription logic, knowing exactly what plan data is coming in—no external API calls required!
By the end of the episode, you'll see how clean and powerful mocking actions can be, making your tests more predictable and your code easier to maintain. If you're using (or considering) the Laravel Actions package, this is a must-know feature!