Skip Laravel's FormRequest Validation

大城市里の小女人 提交于 2021-02-08 19:35:44

问题


I've recently added HaveIBeenPwned to my form request class to check for cracked passwords. Given that this makes an external API call, is there a way for me to skip either this validation rule or the FormRequest class altogether during testing?

Here's the request I make in my test.

    $params = [
        'first_name' => $this->faker->firstName(),
        'last_name' => $this->faker->lastName(),
        'email' => $email,
        'password' => '$password',
        'password_confirmation' => '$password',
        'terms' => true,
        'invitation' => $invitation->token
    ];


    $response = $this->json('POST', '/register-invited', $params);

The functionality I'm testing resides on a controller. In my test I POST an array of data that passes through a FormRequest with the following rules.

 public function rules()
 {
 return [
  'first_name' => 'required|string|max:70',
  'last_name' => 'required|string|max:70',
  'email' => 
  'required|email|unique:users,email|max:255|exists:invitations,email',
  'password' => 'required|string|min:8|pwned|confirmed',
   'is_trial_user' => 'nullable|boolean',
   'terms' => 'required|boolean|accepted',
    ];
  }

I want to override the 'pwned' rule on the password so I can just get to the controller without having to worry about passing validation.


回答1:


With the information provided I'd say you are executing an integration test which does an actual web request. In such a context I'd say it's fine for your test suite to connect to a 3rd party since that's part of 'integrating'.

In case you still prefer to mock the validation rule you could swap out the Validator using either the swap

$mock = Mockery::mock(Validator::class);
$mock->shouldReceive('some-method')->andReturn('some-result');
Validator::swap($mock);

Or by replacing its instance in the service container

$mock = Mockery::mock(Validator::class);
$mock->shouldReceive('some-method')->andReturn('some-result');
App:bind($mock);

Alternatively you could mock the Cache::remember() call which is an interal part of the Pwned validation rule itself. Which would result into something like

Cache::shouldReceive('remember')
   ->once()
   ->andReturn(new \Illuminate\Support\Collection([]));


来源:https://stackoverflow.com/questions/57379527/skip-laravels-formrequest-validation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!