To address the issue of Log::channel('logistics') returning null when using Log::spy(), you need to ensure that the spy method is applied to the specific logging channel you are using in your application. By default, Log::spy() only mocks the default logging channel, not any custom channels you might have defined.
Here's how you can modify your test to spy on the specific logistics channel:
- Use
Log::channel('logistics')->spy()to mock thelogisticschannel. - Ensure that you are checking the logs on the
logisticschannel in your assertions.
Here is the updated test code:
use Illuminate\Support\Facades\Log;
public function testValidationFailureLogsCorrectly()
{
// Spy on the 'logistics' channel
Log::channel('logistics')->spy();
$location = factory(Location::class)->create();
$case1 = factory(Case::class)->create();
$this->postJson(
'logistics/delivery',
[
'location_id' => $location->uuid,
'contents' => [
$case1->serial,
],
]
)
->assertUnprocessable();
Log::channel('logistics')->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;
});
}
Explanation:
-
Spying on the Specific Channel:
Log::channel('logistics')->spy();ensures that thelogisticschannel is being mocked. -
Assertions on the Specific Channel:
Log::channel('logistics')->shouldHaveReceived('info')ensures that the assertions are made on thelogisticschannel.
By making these changes, you ensure that the logistics channel is properly mocked and that your test can correctly verify the log entries.