For validation tests, I use @dataProvider and write a single test that uses it (which will be ran once for each data row)
/**
* @test
*
* @dataProvider provideValidationData
*/
public function returns_json_validation_errors_when_validation_fails($field, $value)
{
// any setup required
$this->postJson(route('URL'), $this->validParams([$field => $value])))
->assertStatus(422)
->assertJsonValidationErrors($field);
// I would then also check that data wasn't either inserted or updated
}
public function provideValidationData()
{
return [
'name_required' => ['field' => 'name', 'value' => ''],
'email_required' => ['field' => 'email', 'value' => ''],
'email_is_email' => ['field' => 'email', 'value' => 'not-an-email'],
];
}
// Just a method to provide default valid data, so we are only testing the single field
protected function validParams($overrides = [])
{
return array_merge([
'name' => 'John Smith',
'email' => '[email protected]',
], $overrides);
}