1

我正在运行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');
}

2 个调用中的每一个$this->get()似乎都在调用具有相同查询字符串参数q=值的路由,doe因此第二组断言失败,因为它还返回 3 条记录。

在浏览器中进行测试时,一切正常,并且记录由查询字符串过滤 - 只是在测试期间 - 就好像调用第二次忽略参数一样。

routehelper 使用查询字符串返回正确的 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);
}

知道可能是什么原因造成的吗?

4

0 回答 0