Skip to content

User factored model for authentication persists wasRecentlyCreated to true when recalled by the endpoint's controller #21107

@danielebriggi

Description

@danielebriggi
  • 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:

  1. create an endpoint that accepts PATCH
  2. 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
  1. create a unit test
  2. factory an User model and authenticate it with Passport: Passport::actingAs(factory(User::class)->create());
  3. call the endpoint and assert the status is 200: $this->patchJson(...)->assertStatus(200);
  4. it's expected to be 200 instead is returned 201

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions