laravel / scout

Laravel Scout provides a driver based solution to searching your Eloquent models.
https://laravel.com/docs/scout
MIT License
1.54k stars 327 forks source link

Add a fake() for scout #806

Closed chrisrhymes closed 6 months ago

chrisrhymes commented 6 months ago

Is it possible to add something like Scout::fake(); that would act similar to the Http::fake()? The idea for this would be to allow end to end tests to be run and allowing you to provide the data that should be returned. It could also prevent any stray http requests being sent to meiliesearch, algolia, etc.

My use case is that I am finding it difficult to figure out how to run tests in a CI pipeline without access to a live instance of meilisearch. I also can't use the database or collection drivers as I have customised the search to allow geo filtering that is specific to meilisearch, as well as creating additional fields from relations that are not in the original model (as per this example with the company_name).

As a code example, I was thinking something like the following:

Scout::fake([
    '*' => collect([User::factory()->create(['name' => 'Dave'])]),
]);
Scout::preventStrayRequests();

$users = User::search('dave')->paginate();
driesvints commented 6 months ago

For testing, you should set the Scout driver to null in your phpunit.xml:

<env name="SCOUT_DRIVER" value="null"/>
chrisrhymes commented 6 months ago

Ok, will do. But now this returns no results for my API tests?

As an example, the API controller for this route uses Laravel Scout to search the Service models. The test now fails as scout returns no results.

Service::factory()->create([
    'name' => 'Test service',
]); 

getJson(route('api.v1.services', ['name' => 'test']))
        ->assertStatus(200)
        ->assertJsonCount(1, 'data');
driesvints commented 6 months ago

I don't think there's a way to do what you want. If you have Meilisearch specific things you'll need to start a meilisearch docker service in your CI and actually hit a meilisearch DB. I don't think we'll add a Scout fake ourselves anytime soon, sorry.

chrisrhymes commented 6 months ago

Ok. Thank you for your help!