donglu6805 2017-11-30 14:42
浏览 55
已采纳

Laravel phpunit assertViewHas与预期的测试数据不匹配

I am writing a test for my search method, but had currently a assertSee and want to change it for a assertViewHas for a better test result. But the data that I get from the search method does not want to match the data I expect.

This is where I set $user:

protected $user;

public function setUp()
{
    parent::setUp();

    $this->seed();

    $this->user = factory(User::class)->create(['role_id' => 3]);
}

This is where I'm making the assertion:

$response = $this->followingRedirects()->actingAs($this->user)->get('/manage/users/search?choices=username&search='.$this->user->username.'');

$response->assertViewIs('manage.users');
$response->assertSuccessful();
$response->assertViewHas('users', $this->user);

And this is the data it will return from the controller:

$result = User::where('username', 'LIKE', '%'. $request->get('search') .'%')
                ->orderBy('username', 'asc')->paginate(20);
return view('manage.users')->with('users', $result);

What am I doing wrong to get the matching data?

  • 写回答

1条回答 默认 最新

  • dqef7931 2017-11-30 16:55
    关注

    You are trying to assert that $this->user matches $users from your controller. But paginate() returns a LengthAwarePaginator instance and $this->user is an instance of User, so they won't match.

    If you want to assert that a given user is contained in the $users variable passed to the view, you could pass a closure to assertViewHas() with the necessary logic.

    Maybe something like this:

    $response->assertViewHas('users', function($users) {
        return $users->contains($this->user);
    });
    

    You can view how assertViewHas() works on the Laravel source code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器