gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 21:22:09 25 4
gpt4 key购买 nike

我正在编写一个用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com