我正在运行Laravel 5.6
,在使用查询字符串测试终点时遇到了一个奇怪的问题。
这是我的测试:
/**
* @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');
}
两个$this->get()
调用中的每一个似乎都在调用查询字符串参数q
= doe
的相同值的路由,因此第二组断言失败,因为它也返回3条记录。
在浏览器中进行测试时,一切正常,记录会被查询字符串过滤 - 它只是在测试过程中 - 好像调用第二次忽略了参数。
route
helper使用查询字符串返回正确的url。
我的控制器有这样的东西:
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);
}
知道可能导致它的原因吗?