Laravel Scout Array Driver for Testing
Published on by Paul Redmond
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:
$user = factory(User::class)->create([ 'name' => 'Oliver',]); $user2 = User::withoutSyncingToSearch(function () { return factory(User::class)->create([ 'name' => 'John', ]);}); Search::assertContains($user) // passes ->assertContains($user2) // fails ->assertContains($user, function ($record) { // passes return $record['name'] === 'Oliver'; }) ->assertContains($user, function ($record) { // fails return $record['name'] === 'John'; }) ->assertContains($user2, function ($record) { // fails return $record['name'] === 'John'; });
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.
$user = factory(User::class)->create([ 'id' => 123, 'name' => 'Peter', 'email' => 'peter@example.com',]); Search::fakeRecord($user, [ 'id' => 123, 'name' => 'John',], false); $record = User::search()->where('id', 123)->raw()['hits'][0]; $this->assertEquals('Peter', $record['name']); // fails$this->assertEquals('John', $record['name']); // passes$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.