我定义了一个测试用户创建的测试。 Controller 设置为在出错时重定向回同一页面(通过生成的 App\Http\Requests\Request
使用验证)。这在浏览器中手动单击时可以正常工作,但在测试期间会失败。而不是被重定向到:
http://localhost/account/create
测试重定向到(缺少斜杠):
http://localhostaccount/create
这些 url 都不是我在 .htaccess 或 config/app.php 中的 $url
变量中设置的。这是(在 OSX Yosemite 上):
http://~username/laravel_projects/projectname/public
我最终指出问题与 Request::root()
的结果生成方式有关。在测试之外调用它会产生 .htaccess 和 $url
中定义的预期值。在测试中它导致:
http://localhost
为了让这个函数在两种情况下都返回正确的值,需要更改什么配置?
我还应该提到我从 Laravel 4 痛苦地升级到当前版本 5.0.27。
****** 更新 *******
我能够找到一个可接受的解决方案/变通方法来解决这个问题!
在 Laravel 5 中,引入了 FormRequests 来帮助移动 validation逻辑出 Controller 。将请求映射到 Controller 后,如果指定了 FormRequest
(或只是 Request
),则会在点击 Controller 操作之前执行。
如果验证失败,此 FormRequest
默认处理响应。它会尝试根据您将表单数据发布到的路由构建重定向。在我的例子中,可能与我从 Laravel 4 更新到 5 的错误有关,这个默认重定向构建不正确。 Laravel System处理响应的代码如下所示:
/**
* Get the proper failed validation response for the request.
*
* @param array $errors
* @return \Symfony\Component\HttpFoundation\Response
*/
public function response(array $errors)
{
if ($this->ajax() || $this->wantsJson())
{
return new JsonResponse($errors, 422);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
请注意返回的重定向与调用 Redirect::route('some_route')
的方式不同。你可以override这个 response
函数通过在你的 Request
类中包含 use Response
来实现。
在使用 Redirect::route()
创建重定向后,我的测试逻辑通过了预期结果。这是我有效的请求代码:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Http\Requests\Request;
use Response;
class AccountRequest extends FormRequest {
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'email' => 'required|max:50|email|unique:users',
'password' => 'required|min:6',
'password_confirmation' => 'required|same:password'
];
}
public function response(array $errors){
return \Redirect::route('account_create');
}
}
重要的是我调用了 Redirect::route 而不是让默认响应代码执行。
最佳答案
Override the response function在 FormRequest 验证处理程序中强制使用 Redirect::route('named_route') 构造重定向,而不是允许默认重定向。
关于php - 在 Laravel 5 中,为什么在 phpunit 测试期间调用 Request::root() 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29483677/