在测试控制器时,是否有一种完全跳过授权的内置方式?
样本控制器:
public function changePassword(Request $request, LdapInterface $ldap)
{
$this->authorize('change-password');
$this->validate($request, [
'pass' => 'min:8|confirmed|weakpass|required',
]);
$success = $ldap->updatePassword($request->get('pass'));
$message = $success ?
'Your e-mail password has been successfully changed' :
'An error occured while trying to change your alumni e-mail password.';
return response()->json(['message' => $message]);
}我想跳过change-password规则,它在AuthServiceProvider中定义如下:
public function boot(GateContract $gate)
{
$gate->define('change-password', function ($user) {
// Some complex logic here
});
}我不想增加smt。就像代码中的if (env('APP_ENV') == 'testing') return;。
发布于 2017-10-30 14:33:29
我不知道,但是您可以将检查移到专用中间件上,并使用withoutMiddleware特性在测试中禁用它。
或者,您可以使用嘲讽来模拟应用程序的门实例。嘲弄是有详细记录的,因此我建议阅读文档以获得更多细节,但设置它的方式如下所示:
$mock = Mockery::mock('Illuminate\Contracts\Auth\Access\Gate');
$mock->shouldReceive('authorize')->with('change-password')->once()->andReturn(true);
$this->app->instance('Illuminate\Contracts\Auth\Access\Gate', $mock);这将建立一个门契约的模拟,设置它期望接收的内容以及它应该如何响应,然后将它注入应用程序。
发布于 2017-12-15 15:14:02
其实有一种内置的方式。您可以在实际授权检查之前添加要调用的“前面”回调,只需返回true即可绕过检查。
\Gate::before(function () {
return true;
});您应该将此片段添加到您的测试的setUp()方法中,或者添加到您希望使用的每个测试方法中。
发布于 2017-10-30 14:35:22
来自laravel 文档:
在测试应用程序时,您可能会发现为某些测试禁用中间件是很方便的。这将允许您在与任何中间件无关的情况下测试您的路由和控制器。Laravel包含一个简单的
WithoutMiddleware特性,您可以使用它自动禁用测试类的所有中间件:
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
use WithoutMiddleware;
//
}也可以在测试方法中使用withoutMiddleware()方法,如下所示:
public function testBasicExample()
{
$this->withoutMiddleware();
$this->visit('/')
->see('Laravel 5');
}Ps :自Laravel 5.1以来
https://stackoverflow.com/questions/47017307
复制相似问题