Temporary User for testing

Published 1 month ago by f.grande

Hi all, I'm trying to understand which is the best practice to test an API with PHPUnit under Laravel.

    $user = factory(User::class)->create();

    $response = $this->actingAs($user)
                     ->get('/xyz/aaa/bbb/ccc');

    $response->assertStatus(200);

My /xyz route is under auth, so I need to access if acting as an authenticated user.

Creating a new user is the answer (I think) but if I launch 10 times the test, I'll create 10 users (of course !)

Which is the right (or the best) way to create a "temporary" user to test my API ?

Should I leverage on SetUp and TearDown methods ? Or there's a better way ?

Thanks in Advance FabioG

zion
zion
1 month ago (26,530 XP)

Use an in memory sqlite database for testing with the refreshDatabase trait. This will not touch your regular database but a temporary memory database which will be rebuild each time.

tykus
tykus
1 month ago (690,940 XP)

I use a specific testing database and the RefreshDatabase trait, so every test will create the user it needs, and then discards those records.

Whether I use a setUp method in the tests class will depend; for example, sometimes the user might have slightly different attributes/permissions etc in the context of different test examples; other times it is a similar user for every test example.

Laravel's model factories are a great tool for creating exactly the world you need for each and every test, so use them!

Please sign in or create an account to participate in this conversation.