PhpSpec test if log written with same data

67 Views Asked by At

I need to test if my application logs written with correct data (I know in most cases it's not very important to check logs, but it's very important in this specific case).

So log looks like this:

 $this->logger->error(
       'Invalid survey provided',
        [
            'exception' => $e,
            'survey' => $survey
        ]
 );

and in the spec I have a code:

        $exception =  new ValidationException(
            sprintf(
                'Provided survey "%s" does not have all required fields %s',
                json_encode($surveysResponse['result'][0]),
                json_encode(Survey::$requiredFields)
            )
        );
        $logger->error(
            'Invalid survey provided',
            [
                'exception' => $exception,
                'survey' => $surveysResponse['result'][0]
            ]
        )->shouldBeCalled();

and spec failing b-z mock not matching, but I'm sure that same error message with same survey and exception with same error message actually logged. I'm not able to tell you exact issue as error output is huge and trimmed. But I'm 90% sure it's failing while comparing exception object because exceptions are not exact the same objects.

1

There are 1 best solutions below

0
Martin Zeitler On

This might be the wrong approach, because the log entry will not be the same due to different timestamps on the log entry. Just preg_match() the log file, spanning multiple lines, obviously with a wildcarded timestamp. Then it should be save to assume that they're "the same", when the count of returned matches equals two (assuming a truncated log file, to begin with). Check out \PHPSpec\Matcher .beTrue() in combination with said condition.