Do you test all validations for create and update actions?

Published 7 months ago by rikw

Hi!

I'm writing tests for my new application and start to wonder... Do you test all form field validations for create and update actions seperately? To me it looks like a lot of test code. Does that make sense?

Cheers! Rik

Best Answer (As Selected By rikw)
tykus

I do; for me a lot of test code is preferrable to untested business rules.

If it helps, I usually create a validParams helper method in my test class which will return an array of valid form parameters. It will, however, accept overrides which allows my test example to be explicit about which input is under test, e.g.

/** @test */
function it_will_not_register_a_user_without_an_email()
{
    $this->call('api/users', $this->validParams(['email' => '']))->assertStatus(422);
}

/** @test */
function it_will_not_register_a_user_if_email_is_not_unique()
{
    $existingUser = factory(App\User::class)->create(['email' => '[email protected]']);

    $this->call('api/users', $this->validParams([email' => '[email protected]']))
        ->assertStatus(422);
}

private function validParams($overrides = [])
{
    return array_merge([
        'name' => 'John',
        'surname' => 'Doe',
        'email' => '[email protected]'
    ], $overrides);
}

For me, this results in test which are more clear and concise tests while ensuring that all paths in my app are covered.

tykus
tykus
7 months ago (618,840 XP)

I do; for me a lot of test code is preferrable to untested business rules.

If it helps, I usually create a validParams helper method in my test class which will return an array of valid form parameters. It will, however, accept overrides which allows my test example to be explicit about which input is under test, e.g.

/** @test */
function it_will_not_register_a_user_without_an_email()
{
    $this->call('api/users', $this->validParams(['email' => '']))->assertStatus(422);
}

/** @test */
function it_will_not_register_a_user_if_email_is_not_unique()
{
    $existingUser = factory(App\User::class)->create(['email' => '[email protected]']);

    $this->call('api/users', $this->validParams([email' => '[email protected]']))
        ->assertStatus(422);
}

private function validParams($overrides = [])
{
    return array_merge([
        'name' => 'John',
        'surname' => 'Doe',
        'email' => '[email protected]'
    ], $overrides);
}

For me, this results in test which are more clear and concise tests while ensuring that all paths in my app are covered.

rikw
rikw
7 months ago (1,490 XP)

Thank you @tykus, this is the confirmation I was looking for. I did more or less the same.

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