首页 > 解决方案 > 测试要为用户显示的错误消息

问题描述

我正在尝试编写一个测试来断言当用户输入错误的用户名或密码时我的登录页面显示错误。

    @if ($errors->any())
      <p>Looks like you’ve entered the wrong username or password. 
        <a href="{{route('password.request')}}">
           Click here</a> to reset your  password“ </p></div>
    @endif        

该功能运行良好,我可以在页面上看到错误,但由于某种原因,我无法通过测试。

->assertSessionHasErrors() 工作正常,而 ->assertSeeText() 没有检测到文本中的错误消息。`

public function userSeesErrorMessage() {
  $user = factory('App\User')->create([
        'password' => bcrypt($password = 'test'),
    ]);
    $response = $this->followingRedirects()
    ->post('/login', [
        'email' => $user->email,
        'password' => 'incorrectPassword'
    ]);
    $response->assertSeeText('Looks like you’ve entered the wrong username or password. Click here to reset your password');
}`

响应似乎包含整个文档的 HTML,除了关于错误的部分。

任何帮助将非常感激。

标签: phplaravel

解决方案


这不起作用可能有几个原因。您可以做的最简单的事情是为引用者设置标题。这样,验证将知道将您重定向回哪里,因为当前您没有提交表单,并且重定向会将您发送到您可能不会显示错误的页面:

$response = $this->followingRedirects()
    ->post(
        '/login', 
        [
            'email' => $user->email,
            'password' => 'incorrectPassword'
        ], 
        ['referer' => '/login']
    );

另一个问题可能是重定向中丢失了会话错误,您可以尝试单独跟踪重定向:

$r = $this->post('/login', [
        'email' => $user->email,
        'password' => 'incorrectPassword'
    ]);

$r->assertStatus(302);
$r->assertSessionHasErrors('email');

$r = $this->followRedirects($r);

$r->assertSeeText('Looks like you’ve entered the wrong username or password. Click here to reset your password');

推荐阅读