I'm running Laravel 5.6
and came across a weird issue while testing end points with query string.
Here's my test:
/**
* @test
*/
public function returns_records_filtered_by_search()
{
factory(NewsletterSubscriber::class)->states('verified')->create([
'email' => 'jon@doe.com',
'first_name' => 'Jon',
'last_name' => 'Doe',
]);
factory(NewsletterSubscriber::class)->states('verified')->create([
'email' => 'jane@doe.com',
'first_name' => 'Jane',
'last_name' => 'Doe',
]);
factory(NewsletterSubscriber::class)->states('verified')->create([
'email' => 'jeremy@doe.com',
'first_name' => 'Jeremy',
'last_name' => 'Doe',
]);
$response = $this->get(route('admin.newsletter_subscriber', ['q' => 'doe']));
$response->assertStatus(Response::HTTP_OK)
$response->assertSee('Subscribers (3)');
$response->assertSee('jon@doe.com');
$response->assertSee('jane@doe.com');
$response->assertSee('jeremy@doe.com');
$response = $this->get(route('admin.newsletter_subscriber', ['q' => 'jane']));
$response->assertStatus(Response::HTTP_OK)
$response->assertSee('Subscribers (1)');
$response->assertDontSee('jon@doe.com');
$response->assertSee('jane@doe.com');
$response->assertDontSee('jeremy@doe.com');
}
Each of the 2 $this->get()
calls seem to be calling the route with the same value for the query string parameter q
= doe
and hence the second set of assertions fails as it also returns 3 records.
When tested in browser it all works fine and records are filtered by the query string - it's just during tests - as if the call was ignoring parameters second time around.
route
helper returns correct url with the query string.
My controller has something like this:
public function index(Request $request): View
{
$query = NewsletterSubscriber::verified();
if (!is_null($q = $request->get('q'))) {
$query->where(function(Builder $query) use ($q) {
$query->where('email', 'like', '%'.$q.'%')
->orWhere('first_name', 'like', '%'.$q.'%')
->orWhere('last_name', 'like', '%'.$q.'%');
});
}
$subscribers = $query->orderBy('created_at', 'desc')->paginate(10);
return $this->view('newsletter-subscriber.index')
->with('subscribers', $subscribers);
}
Any idea what might be causing it?