43

Laravel Scout Array Driver for Testing

 4 years ago
source link: https://www.tuicool.com/articles/NzEbAfN
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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' => '[email protected]',
]);

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 .

Filed in: News / Scout


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK