How to test NewSubcription without hitting Stripe API?
Hi guys,
I'm currently working on a project which I'm setting up tests on, however I've hit a wall and I'm struggling to find out how to fix this.
So, I have a part of my code which when a user creates a new item on the system it requires them to subscribe using Stripe payment. This is working fine. However, I have been setting up tests whilst building up this project, but now my test which was checking if the new item was created fails as it is reaching the Stripe API - this not only slows tests down but it's also not creating the item in the database and not creating the new subscription (hence the test not passing).
How can I tell my tests to not access the Stripe API, and to just mock up a response, or something similar, which will result in the various database tables being updated (such as subscriptions being added).
In my code I have the following.
An InstructorsController which is responsible for the creation of the item which is going to have a subscription associated with it.
public function store() {
... snipped ...
$stripeToken = request('stripeToken');
$user = User::find(auth()->user()->id);
$user->newSubscription('instructor', config('services.stripe.plan'))
->create($stripeToken, [
'email' => $user->email
]);
$instructor = Instructor::create([
... snipped ...
]);
if(request()->wantsJson()) {
return response($instructor, 201);
};
event(new InstructorCreated($instructor));
return redirect(route('index'))
->with('flash.success', 'Your instructor has been submitted for review!');
}
}
My User model has the Billable trait - so that the Cashier works as expected.
So, my question is, is there a way to tell my tests that for the newSubscription() method to not use Stripe and to just assume that all is good? Or is it possible to Mock up a Stripe response to be used during testing?
Currently to get things to pass I have just wrapped the newSubscription logic in...
if(! \App::runningUnitTests()) { }
... this has allowed tests to pass but it doesn't create any of the subscription database data, so when I come to test that it isn't available to be tested.
I'm not overly interested in testing the Stripe API itself.
Any help would be very gratefully appreciated as I'm really not sure the best way to resolve this.
Thanks!
EDIT - The test which I have set up to check if a user can create a new instructor is:
/**
* @test
*/
public function an_authenticated_and_verified_user_can_create_instructors() {
$this->signIn();
$instructor = make('App\Instructor');
$this->post(route('instructor.store'), $instructor->toArray() + ['stripeToken' => 'some value']);
$this->assertDatabaseHas('instructors',
['name' => $instructor->name]
);
}
In above my make() function is just a quick way of creating a factory isntance of App\Instructor. I have overridden the stripeToken as a value is required when posting a new instructor.
Please or to participate in this conversation.