stefr's avatar
Level 9

Disable one validation rule in test

Hi, I'm writing an application test for a signup form. In the form there are a lot of validation rules. I would like to dissable just one rule in my test since this is an external validation to an api. (https://github.com/dannyvankooten/laravel-vat). So I want to dissable the "vat_number" rule on the "vat" field. I can't figure out the right way to do this.

0 likes
6 replies
iamine's avatar

i know it's a quit old question, but i was looking for an answer for a similar issue. i found that you can make a condition for rules to check if the app is in testing envirement.

public function rules() {

if (app()->environment('testing')) {
	return [
		'field' => ['required'],
		'field2' => ['required'],
	];
}

return [
		'field' => ['required'],
];
}
martinbean's avatar

@iamine You’re not testing your application if you’re randomly turning bits on and off in tests, though.

iamine's avatar

@martinbean i did this only for "ReCaptcha", i turn off recaptcha validation during the test.

martinbean's avatar

@iamine I use reCATPCHA in applications. I don’t disable the validation rule, though; I mock the reCAPTCHA service to return the values I want. This means I can test both successful and failed reCAPTCHA responses instead of just going, “Well, this is a test, so I’m not even going to both with this rule”.

protected function setUp(): void
{
    parent::setUp();

    $this->captcha = $this->mock(Captcha::class);
}

public function testCaptchaPassesWithGoodValue(): void
{
    $this->captcha->shouldReceive('verify')->with('GOODVALUE')->andReturn(true);

    $response = $this->post('/some-uri-that-uses-recpatcha', [
        'g-recaptcha-response' => 'GOODVALUE',
    ]);

    $response->assertSuccessful();
}

public function testCaptchaFailsWithBadValue(): void
{
    $this->captcha->shouldReceive('verify')->with('BADVALUE')->andReturn(false);

    $response = $this->post('/some-uri-that-uses-recpatcha', [
        'g-recaptcha-response' => 'BADVALUE',
    ]);

    $response->assertSessionHasErrors('g-recaptcha-response');
}

So, now I no longer have horrible if statements in my application code checking if it’s being ran in a test or not, and turning things on and off just for the sake of getting a test to pass.

1 like

Please or to participate in this conversation.