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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With