-
Notifications
You must be signed in to change notification settings - Fork 11.6k
Description
- Laravel Version: 5.5.0
- PHP Version: 7.1
- Database Driver & Version: MySql 5.7.19
Description:
Context: unit testing.
For unit testing API that requires the Passport authentication is suggested to factory an user instance and give it to Passport: Passport::actingAs(factory(User::class)->create());
In my case I needed to test the PATCH /users
API.
I did as suggested but the response from the user resource's response returned by the enpoint's controller was 201 instead of 200.
The problem was related to the Model::$wasRecentlyCreated
property (https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Model.html).
When user is factored the property is set to true
. When the unit test calls $this->patchJson(...)
endpoint and the enpoint's controller recalls the logged user by Auht::user()
the $wasRecentlyCreated
is still set to true
.
The way to fix the test is to fresh()
the user model: Passport::actingAs($user->fresh())
.
I'm not sure it's a bug but it's an unexpected behavior to me. I'd expected that model retrieved from, eg, the Auth facade, be in a fresh state just like the request is coming from a real request.
Steps To Reproduce:
- create an endpoint that accepts PATCH
- in the endpoint's controller
- recall the user:
Auth::user()
- update some user's attributes and save
- return the user's resource model with the updated user
- create a unit test
- factory an User model and authenticate it with Passport:
Passport::actingAs(factory(User::class)->create());
- call the endpoint and assert the status is 200:
$this->patchJson(...)->assertStatus(200);
- it's expected to be 200 instead is returned 201