Laravel Scout Array Driver for Testing

News

August 28th, 2019

laravel-scout-featured.png

Laravel Scout Array Driver is a package by @Sti3bas that provides conveniences around testing Laravel Scout search:

This package adds an array driver to Laravel Scout and provides custom PHPUnit assertions to make testing search-related functionality easier.

The package ships with a Search facade which provides convenience methods that make asserting search easier:

1$user = factory(User::class)->create([
2 'name' => 'Oliver',
3]);
4 
5$user2 = User::withoutSyncingToSearch(function () {
6 return factory(User::class)->create([
7 'name' => 'John',
8 ]);
9});
10 
11Search::assertContains($user) // passes
12 ->assertContains($user2) // fails
13 ->assertContains($user, function ($record) { // passes
14 return $record['name'] === 'Oliver';
15 })
16 ->assertContains($user, function ($record) { // fails
17 return $record['name'] === 'John';
18 })
19 ->assertContains($user2, function ($record) { // fails
20 return $record['name'] === 'John';
21 });

The Search facade has a bunch of methods you should check out in the readme. One that stood out to me was the fakeRecord method. This method allows you to fake search index record of the model.

1$user = factory(User::class)->create([
2 'id' => 123,
3 'name' => 'Peter',
4 'email' => 'peter@example.com',
5]);
6
7Search::fakeRecord($user, [
8 'id' => 123,
9 'name' => 'John',
10], false);
11
12$record = User::search()->where('id', 123)->raw()['hits'][0];
13
14$this->assertEquals('Peter', $record['name']); // fails
15$this->assertEquals('John', $record['name']); // passes
16$this->assertTrue(!isset($record['email'])); // passes

You can learn more about this package, get full installation instructions, and view the source code on GitHub at Sti3bas/laravel-scout-array-driver.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.