Summer Sale! All accounts are 50% off this week.

BernardoBF4's avatar

Should I write more states in my factories?

In an application using TDD that I am developing right now, I am creating the data I need for store, update and delete endpoints using the WithFaker trait, so it means I have a lot of

$user_data = [
      'fk_groups_id' => Group::factory()->has(Modules::factory(), 'modules')->create()->id,
      'usu_email' => $this->faker->safeEmail(),
      'usu_name' => $this->faker->name(),
      'usu_password' => $this->faker->password(6, 12),
      'usu_password_confirmation' => $this->faker->password(6, 12),
    ];

all around my code. The example above is a test where I am checking that updating a user if the password and password confirmation don't match returns an error.

In this case would be better to keep it like this: to write arrays of data and send to the endpoints and make the asertions, or it would be better to write states inside my factories and just call the factories with the respective state for each test case?

0 likes
1 reply
martinbean's avatar

@bernardobf4 I only really use factories for actually inserting records into my database during tests. For testing validation, I’ll just specify the request data as arrays:

public function testPasswordMustBeConfirmed(): void
{
    $response = $this->post('/register', [
        'password' => 'secretpassword',
        'password_confirmation' => 'notsecretpassword',
    ]);

    $response->assertSessionHasError('password');
}
1 like

Please or to participate in this conversation.