2

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.

Zakalwe
  • 1,444
  • 3
  • 14
  • 25
  • I am interested to know more as well. I have been doing some thinking recently and was wondering if we'd actually need to test validation logic. I mean Laravel already does that. It shouldn't be our responsibility right? Maybe what we can test is whether our fields are getting the appropriate validation rules instead. – Mozammil Jan 28 '19 at 17:15
  • 1
    Given this a bit of thought and I wonder if testing all validation is more feature testing than unit testing. We know Laravel will generate errors correctly (this has been tested internally) so we should be okay just testing that one rule (any rule) occurs and is displayed which should be done via the controller. I think testing all rules is more feature testing where you want to test combinations to ensure they pass or fail and show the right message. Not sure this last step is actually needed but I often change the default error message text so would be useful to know that this text is used. – Zakalwe Feb 04 '19 at 10:42

0 Answers0