I
I
ildar-meyker2021-01-27 12:56:02
Test Driven Development
ildar-meyker, 2021-01-27 12:56:02

When testing, should you create a user in each test method, or is there a better approach?

I write tests where I check whether users of various kinds have the right to perform various kinds of actions. Guest, logged in, admin, etc. Now it looks like this.

class PostsCRUDTest extends TestCase
{
    public function test_guest_has_to_be_verified_user_when_gets_posts_create()
    {
        $response = $this->get('/posts/create');
        $response->assertRedirect('/email/verify');
    }

    public function test_authorised_user_has_to_be_verified_when_gets_posts_create()
    {
        $user = User::factory()->create([
            'email_verified_at' => null
        ]);
        $response = $this->actingAs($user)->get('/posts/create');
        $response->assertRedirect('/email/verify');
    }

    public function test_verified_user_succeeds_when_gets_posts_create()
    {
        $user = User::factory()->create();
        $response = $this->actingAs($user)->get('/posts/create');
        $response->assertStatus(200);
        $response->assertSee('Добавить пост');
    }
}

And it begins to seem that it is better to prepare users in advance. Can I do it in class properties and would that be better overall?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2021-01-27
@ildar-meyker

In the setUp method of the test class, you can set the initial data for all tests. Before each test, all objects will be created from scratch, as they should be. In this example, it is not necessary to bring the user into the setup. in all three tests the data is different. But, for example, an unauthorized user can be taken out in TestCase or traits and call getUnverifiedUser.

K
k2lhu, 2021-01-27
@k2lhu

Each test should check one thing, so to test different groups of users, you can load them in advance as you like in the method . And now in your test, you create a user and execute a POST request to get his rights to something. In the test for checking user rights, the error of creating a user should not fall, and now you have such an opportunity to fail this case. The simpler and shorter the test is, the better and easier it is to write them, the easier it will be to add further verification of some logic around the basic actions, including creating users and checking access rights.
public function _before() {}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question