php - 使用 Laravel Scout 索引的模型测试失败

标签 php laravel phpunit laravel-scout

我正在编写一个用 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.');
    }
}

最佳答案

你到底在测试什么?你只是在测试 ::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; <env name="SCOUT_DRIVER" value="null"/>

关于php - 使用 Laravel Scout 索引的模型测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44848718/

相关文章:

php - define() 中的翻译消息

php - 使用通配符搜索数组键

php - 最佳实践 : Where to Add Email Error Logging in a Laravel 5 App

jquery - Laravel API,请求 header 字段预检响应中的 Access-Control-Allow-Headers 不允许授权

php - 使用 PHPUnit 测试 Guzzle 调用时无法找到包装器

使用命名空间时找不到 PHP 类

php - 使用一个已知变量对 3 个表进行内连接

php - Laravel 4 从联系表单到管理员电子邮件

php - 无法在@dataProvider PHPUnit 中返回对象

php - Zend 表单 : How to pass parameters into the constructor?