lundi 28 janvier 2019

Testing FormRequests in Laravel

I just wanted to know what the best method is for testing against FormRequests and Controllers - in particular how the validation logic can be tested.

As an example, I have a form request (PersonRequest) class set up with the following:

public function rules()
{
    return [
        'name' => 'required',
        'address' => 'required',
        'email' => 'email|required',
        'website' => 'nullable|url'
    ];
}

And then in my controller, I have written tests for:

public function it_can_store_a_person();
public function it_cannot_store_a_person_without_a_name();
public function it_cannot_store_a_person_without_an_address();
public function it_cannot_store_a_person_without_an_email();
public function it_cannot_store_a_person_with_an_invalid_email();
public function it_cannot_store_a_person_with_an_invalid_website();

Then I would have the same functions but for "updating" but this seems to be a repetition of the "storing" test functions.

This all works but seems like overkill and could run into a lot of tests if the criteria were more.

Am I okay to write a seperate test to check the validation rules (an example is given at Unit Test Laravel's FormRequest) and ignore those in the controller and so just test a valid save and an invalid save. i.e.

public function it_can_save_a_person();
public function it_cannot_save_a_person_if_an_error_occurs();

I've also read that FormRequests are tested internally and therefore I should need to test these again.

Any tips, advise on best practices would be gratefully received.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire