【问题标题】:Test with models indexed by Laravel Scout fails使用 Laravel Scout 索引的模型进行测试失败
【发布时间】:2017-12-04 13:07:50
【问题描述】:

我正在编写一个使用 Scout 查找模型的测试。我在 Laravel 5.4 上并使用提供程序 "tamayo/laravel-scout-elastic": "^3.0"

在我开始搜索模型时,似乎在我的测试中索引创建的项目没有完成。这是真的?我怎样才能解决这个问题?我的队列已经设置为sync 并且SCOUT_QUEUE 设置为false

这是一个不断失败的测试示例(断言搜索结果包含给定帖子的失败)。非常感谢任何帮助。

<?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.');
    }
}

【问题讨论】:

  • 您是否尝试过没有嵌套类别的示例,例如只需将父类别添加到帖子中?有效果吗?
  • 不,也不起作用。甚至按标题搜索帖子的测试也失败了:paste.laravel.io/q3XL9.

标签: php laravel phpunit laravel-scout


【解决方案1】:

你到底在这里测试什么?您是否只是测试::search('foo') 返回所需的结果?如果是这样,那么您实际测试 Laravel Scout 的功能是否符合预期,这不是,也不应该是您/我们的工作。

您最多可以测试您是否已正确配置模型以按预期使用 Laravel Scout。

如果一个简单/愚蠢的测试就足够了,那么下面的代码应该会有所帮助;

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()));
    }
}

注意在你的测试环境中禁用 Laravel Scout; &lt;env name="SCOUT_DRIVER" value="null"/&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 2017-10-25
    相关资源
    最近更新 更多