Thanks @remim, but none of the options solves the problem...
Assume a singleton defined on AppServiceProvider::boot() method:
<?php declare(strict_types=1);
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
$this->app->singleton('example', fn() => ['foo', 'bar', 'baz']);
}
}
The first example doesn't change anything because already can use app('example') inside my test:
<?php declare(strict_types=1);
uses(Tests\TestCase::class);
beforeEach(function ()
{
$this->example = app('example')->keyBy('uuid');
});
test('with before each', function()
{
// works OK
expect($this->example)->each->toBeInstanceOff(\App\Models\Example::class);
// is the same as previous and works
expect(app('example'))->each->toBeInstanceOff(\App\Models\Example::class);
});
The point here is to create a reusable dataset, and this doesn't work. I can use the singleton inside the test itself but not in the dataset:
<?php declare(strict_types=1);
uses(Tests\TestCase::class);
dataset('example', function()
{
// throws 'Call to undefined method Illuminate\Container\Container::isBooted()'
$booted = app()->isBooted();
// throws 'Target class [example] does not exist.'
return app('example')->keyBy('uuid');
});
it('working example', function()
{
app()->isBooted(); // true
expect(app('example'))->each->toBeString();
});
it('failing example', function(string $text)
{
expect($text)->toBeString();
})
->with('example');
There is something I don't understand: I checked that the boot method of the AppServiceProvider class, where I set the example singleton, is called before the dataset is loaded. Why is not available?
Anyway, I want a reusable dataset for two reasons:
- It will be use across tens of tests: need to create a lot of tests based on these collections with multiple roles involved
- The output is different: using
expect()->each Pest only shows one line, and with a dataset shows one line per item
So I understand that I cant create a dataset that depends on a fully booted application
Thanks for your help!