Laravel Redirect :: back() - > withErrors()在Test中不起作用

时间:2014-09-19 21:18:23

标签: php laravel laravel-4 integration-testing functional-testing

好的,我在为不正确的凭据编写功能测试时遇到了麻烦。登录即丢失密码。

对于背景,这里是我的路线配置:

Route::get('login', array('as' => 'login', 'uses' => 'SessionController@create'));
Route::resource('session', 'SessionController');

这是我的SessionController :: store()方法中的内容:

public function store()
{

    $credentials = Input::only('email', 'password');

    try {
        $this->loginForm->validate($credentials);

        if (!Auth::attempt(array('email' => $credentials['email'], 'password' => $credentials['password']))) {
            return Redirect::back()->exceptInput('password')->with('flash_message', 'Invalid credentials');
        }

        return Redirect::to('/')->with('flash_message', 'Welcome back');

    }
    catch (FormValidationException $e)
    {
        return Redirect::back()->exceptInput('password')->withErrors($e->getErrors());
    }

}

当我向/ session提交带有POST操作的表单时,上面的store()控制器在浏览器(!)中完美运行。抛出表单验证错误,我被重定向回/ login,在我的视图中使用$ errors变量正确填充相关消息("密码字段是必需的"):

@foreach($errors->all() as $error)
    {{ $error }}
@endforeach

然而,当尝试在功能测试中复制上述预期的工作行为时,我遇到了问题。以下是我测试的基本概要:

public function testIncorrectCredentialsLogin()
{
    $this->client->request('GET', '/login');

    $this->assertTrue($this->client->getResponse()->isOk());

    $credentials = array(
        'email' => 'me@example.com',
        'password' => ''
    );

    $this->client->request('POST', '/session', $credentials);

    $this->assertRedirectedTo('login', array('errors'));

    $crawler = $this->client->followRedirect();

    $this->assertSessionHasErrors();

    $this->assertHasOldInput();

    $this->assertViewHas('errors'); // Fails

}

在我的功能测试中,我尝试复制浏览器中成功发生的事情。我首先进行GET /登录,然后使用缺少的凭据对SessionController :: store()进行/ POST,这会导致验证错误并重定向回/ login。到目前为止一切正常但是当我按照这个重定向回来时,我会在渲染的登录页面内容/ HTML中查看并且我没有设置$ errors变量,因此会话中没有可用的消息/页面中显示。

有人可以告知可能发生的事情吗?

提前致谢。

2 个答案:

答案 0 :(得分:1)

我不是功能测试的专家,但我猜你可能会尝试使用爬虫对象而不是$ this在HTML中找到错误的HTML代码。当你这样做时:

  

$ crawler = $ this-> client-> followRedirect();

对我而言,现在抓取工具通过重定向生成了HTML。

希望有所帮助

答案 1 :(得分:0)

withErrors必须是一个数组

这对我来说有效,因为它是一个数组[]

return redirect()->route('projects')->withErrors(['Something went wrong']);

但这有效。

return redirect()->route('projects')->withErrors('error', 'Something went wrong');