跳过Laravel的FormRequest验证 [英] Skip Laravel's FormRequest Validation
问题描述
我最近在我的表单请求类中添加了 HaveIBeenPwned 来检查破解的密码.鉴于这可以进行外部API调用,我是否可以在测试过程中完全跳过此验证规则或FormRequest类?
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);
我正在测试的功能驻留在控制器上.在我的测试中,我使用以下规则发布了通过FormRequest传递的数据数组.
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',
];
}
我想覆盖密码上的"pwned"规则,这样我就可以直接进入控制器而不必担心通过验证.
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.
推荐答案
根据提供的信息,我想说您正在执行一个集成测试,该集成测试会执行实际的Web请求.在这种情况下,我想说您的测试套件可以连接到第三方,因为这是集成"的一部分.
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'.
如果您仍然希望模拟验证规则,则可以使用 swap
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);
或者,您可以模拟Cache :: remember()调用,该调用是
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([]));
这篇关于跳过Laravel的FormRequest验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!