XSkinner's avatar

Your thoughts about this test

Hello.

I'm starting with testing. I have completed almost all the testing series here at Laracasts, but I'm still not very confident about writing tests though.

So, I'm creating a simple app (API), and one of my tests placed in the Feature folder is as follows.

public function an_authorized_user_can_update_a_given_user_by_id() 
    {
        $user = factory('App\Models\User')->create();

        $newUser = [
            'name' => 'New Test User',
            'email' => '[email protected]',
            'pin' => 90999999,
            'password' => 'newpassword',
            'password_confirmation' => 'newpassword'
        ];

        $response = $this->json('patch', '/api/admin/users/' . $user->id, $newUser);

        $response->assertStatus(200)
            ->assertSee('updated');

        $this->assertDatabaseHas('users', array_except($newUser, ['password_confirmation', 'password']));
    }

Does it make sense for you? Am I writing right tests?

Well actually I have some issues understanding what should be a unit tests, a integrated test or acceptance test. I', using PHPUnit, but I don't know if it is the right tool for all my development.

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

It looks quite good. There are a few comments:

Where are you demonstrating that the user who is making the request is authenticated/authorized?

Any argument could be made that a PATCH request is not appropriate, but I wouldn't labour it.

This is a personal preference, I like to include the form within the request so it is clearer (for me) to see what the request is:

$response = $this->json('patch', '/api/admin/users/' . $user->id, [
    'name' => 'New Test User',
    'email' => '[email protected]',
    'pin' => 90999999,
    'password' => 'newpassword',
    'password_confirmation' => 'newpassword'
]);

If I am performing an assertion that something is in the database as a result of the action, then I will often assert that it is not there before the action.

I don't like assertSee for a JSON response - I would use assertJson or assertExactJson - because you could change your implementation to return a view and that current test would continue to pass.

1 like
XSkinner's avatar

Perfect @tykus thank you for your answer. I'm handling the authentication/authorization in the test's setUp, since all of the related tests require auth.

Regarding patch, yeah, actually I'm used to use PUT instead.

Thank you for your comments.

1 like

Please or to participate in this conversation.