4

我运行了以下测试,我收到一个 failed_asserting 错误为真。有人可以进一步解释为什么会这样吗?

/** @test */
public function a_user_logs_in()
{
    $user =  factory(App\User::class)->create(['email' => 'john@example.com', 'password' => bcrypt('testpass123')]);

    $this->visit(route('login'));
    $this->type($user->email, 'email');
    $this->type($user->password, 'password');
    $this->press('Login');
    $this->assertTrue(Auth::check());
    $this->seePageIs(route('dashboard'));
}
4

2 回答 2

5

您的 PHPUnit 测试是一个客户端,而不是 Web 应用程序本身。因此 Auth::check() 不应返回 true。相反,您可以在按下按钮后检查您是否在正确的页面上,并且您会看到某种确认文本:

    /** @test */
    public function a_user_can_log_in()
    {
        $user = factory(App\User::class)->create([
             'email' => 'john@example.com', 
             'password' => bcrypt('testpass123')
        ]);

        $this->visit(route('login'))
            ->type($user->email, 'email')
            ->type('testpass123', 'password')
            ->press('Login')
            ->see('Successfully logged in')
            ->onPage('/dashboard');
    }

我相信大多数开发人员都会这样做。即使 Auth::check() 有效——它只意味着创建了一个会话变量,你仍然需要测试你是否被正确地重定向到了正确的页面,等等。

于 2016-01-11T06:14:11.210 回答
2

在您的测试中,您可以使用您的模型来获取用户,并且您可以使用 ->be($user) 以便它将获得身份验证。

所以我在我的测试用例中编写了 API 测试

    $user = new User(['name' => 'peak']);
    $this->be($user)
         ->get('/api/v1/getManufacturer')
          ->seeJson([
             'status' => true,
         ]);

这个对我有用

于 2016-12-28T11:12:23.217 回答