Testing with models indexed by Laravel Scout fails
I am writing a test for finding models with a scout. I am on Laravel 5.4 and using a provider "tamayo/laravel-scout-elastic": "^3.0"
.
It looks like in my tests, the indexing of the created items does not complete when I start searching for the model. It's true? How can I fix this? My queue is already set to sync
and SCOUT_QUEUE
set to false
.
Here is an example test that keeps failing (failed to claim that the search results contain the given post). Any help is appreciated.
<?php
namespace Tests\Unit;
use App\Models\Category;
use App\Models\Post;
use App\Models\User;
use Tests\TestCase;
class SearchTest extends TestCase
{
/** @test * */
public function it_searches_the_whole_category_tree_for_posts()
{
// Given
/** @var Category $parentCategory */
$parentCategory = \factory(Category::class)->create([
'title' => 'myParentCategory',
]);
/** @var Category $childCategory */
$childCategory = \factory(Category::class)->create();
$childCategory->makeChildOf($parentCategory);
/** @var Post $post */
$post = \factory(Post::class)->create([
'user_id' => \factory(User::class)->create()->id,
]);
$post->requestCategories()->attach($childCategory);
// When
$searchResults = Post::search('myParentCategory')->get();
// Then
$this->assertTrue($searchResults->contains($post), 'Failed asserting that search results contain the given post.');
}
}
source to share
What exactly are you testing here? Are you just checking what ::search('foo')
returns the results you want? If so, then you are actually verifying that Laravel Scout is functioning as expected, which is not, and should not be your / our job.
In most cases, you can check that you have configured your model correctly to use Laravel Scout as expected.
If a simple / dumb test is enough, then the code below should help:
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class ScoutInstallTest extends TestCase
{
use RefreshDatabase;
/**
* Verify the class uses Laravel Scout
*
* @group scout-install
* @test
*/
public function foo_model_uses_scout()
{
$this->assertTrue(in_array('Laravel\Scout\Searchable', class_uses('App\FooModel')));
}
/**
* Verify that a searchable array does exists, and contains
* the values we desire to search on.
*
* @group scout-install
* @test
*/
public function foo_model_has_valid_searchable_array()
{
$fooModel = factory(\App\FooModel::class)->create();
$this->assertTrue([
'title', // an array of keys that are being indexed.
] === array_keys($fooModel->toSearchableArray()));
}
}
Note: disable Laravel Scout in test environment; <env name="SCOUT_DRIVER" value="null"/>
source to share