I have a FormRequest
that logs validation error details:
protected function failedValidation(Validator $validator)
{
Log::channel('logistics')->info('Validation failed. Submitted serials:', [
'contents' => $this->input('contents'),
]);
...
I want to test that this logs correctly, so in a test I’m doing this:
Log::spy();
$this->postJson(
'logistics/delivery',
[
'location_id' => $location->uuid,
'contents' => [
$case1->serial,
],
]
)
->assertUnprocessable();
Log::shouldHaveReceived('info')
->withArgs(function ($message, $context) use($case1) {
$this->assertStringContainsString('Validation failed. Submitted serials:', $message);
$this->assertArrayHasKey('contents', $context);
$this->assertEquals([$case1->serial], $context['contents']);
return true;
});
This fails in the FormRequest
because after being mocked with spy
, Log::channel('logistics')
returns null
, I assume because the mocked Log
facade contains no channels, but the net result is that it only fails when testing; it works fine normally.
I’m using Log::spy
with Log::shouldHaveReceived
instead of Log::shouldReceive
because there may be other logging calls during the test run, and they create ambiguity that can be avoided with spy
.
I also tried spying on the channel specifically, using Log::channel('logistics')->spy();
, but that doesn’t exist.
If I remove the use of channel()
in both code and test, it works fine.
How should I test this?
4