gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 12:59:42 25 4
gpt4 key购买 nike

这是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com