php - 为什么在进行集成测试时必须重新加载 Auth::user()

标签 php laravel testing router

这是 How to wait for a page reload in Laravel integration testing 的跟进

我正在做的是编辑用户的个人资料,然后重新显示 View 。

我的配置文件操作:(UserController)

public function profile(){
    return view('user/profile');
}

View 包含如下代码

{{ Auth::user()->firstname }}

现在在我的测试中,显示了旧的(未更改的)用户数据。

测试:

protected function editUserProfile()
{
    $this->visit('/user/profile');
    $firstName = $this->faker->firstname;
    $lastname = $this->faker->lastname;

    $this->within('#userEditForm', function() use ($firstName, $lastname) {
        $this->type($firstName, 'firstname');
        $this->type($lastname, 'surname');
        $this->press('Save')
            ->seePageIs('/user/profile')
            ->see($firstName)   # here the test fails
            ->see($lastname);
    });
}

当我像这样更改 UserController 时:

public function profile(){
    Auth::setUser(Auth::user()->fresh());
    return view('user/profile');
}

一切正常。

现在我想明白,为什么会这样。

在那种情况下,为什么集成测试的行为与浏览器不同?是否有更好的方法来调整该行为,以便只有在存在“真正的问题”时测试才会失败?还是我的代码不好?

最佳答案

您可能正在为请求使用 update (int $uid)

最可能的解释是 Laravel 在测试期间只使用了一个应用程序实例。它接受您提供的输入,构建请求对象,然后将其发送到 Controller 方法。它可以从这里呈现 View 并检查它是否包含您的文本。

在身份验证实现中,一旦您调用 Auth::user(),它会做以下两件事之一:

  • 如果没有加载用户,它会尝试从存储中检索它。
  • 如果用户已经加载,则返回它。

您的更新方法(我猜)是从存储中检索用户的新实例并更新它,而不是缓存的实例。

例如:

\Auth::loginUsingId(1234);
\Auth::user()->email; // 'user@example.com'

$user = \App\User::find(1234);
$user->email; // 'user@example.com';

$user->update(['email' => 'user2@example.com']);
$user->email; // 'user2@example.com'

\Auth::user()->email; // 'user@example.com'

关于php - 为什么在进行集成测试时必须重新加载 Auth::user(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39892949/

相关文章:

php - 无法将路由器服务传递给 symfony 2.6 中的 Twig 扩展

php - 批量插入并获取返回的 ID Laravel

php - Laravel 在生产中以编程方式从 web.php 调用 artisan 命令

unit-testing - 在 Laravel 中单元测试 Controller 而不测试路由的最佳方法是什么

php - 在每个页面的页脚中使用 mysqli_close 有什么缺点吗?

php - 返回表中每条记录的平均值

javascript - Protractor - 如何从对象中获取值(value)以在 Promise 之外操纵值(value)

ios - NSObject 在 StoryBoard/Interface Builder 中的作用是什么?

android - 如何同时在多个设备上运行 android Instrument 测试

php - 用于各种用户输入表的 MySQL VARCHAR 与 TEXT