简体   繁体   中英

How to seeInDatabase special characters \r and \n

I have a legacy system which I'm implementing a new integrated feature. This feature is being developed under Laravel Framework and one of my tests relies on seeing a parsed email body inside the database.

    // Assert
    $this->seeInDatabase('ticket', ['title' => 'TDD', 'user_id' => $user->id])
        ->seeInDatabase('interaction', [
            'response' => 'message.\r\n',
            'user_id' => $user->id
        ]);

Problem is:

1) tests\Artisan\InboxTest::it_should_parse_valid_email_and_make_ticket
Unable to find row in database table [interaction] that matched 
attributes 
---> [{"response":"message.\\r\\n","user_id":12}].
Failed asserting that 0 is greater than 0.

Apparently, seeInDatabase escapes the backslashes and looks for message.\\\\r\\\\n , which it will never find because the information is actually message.\\r\\n .

I tried escaping it myself, but got the same result.

TL;DR : how do I get Laravel to see the characters in the database?

The trait:

InteractsWithDatabase

describes the seeInDatabase method:

protected function seeInDatabase($table, array $data, $connection = null)
{
    $database = $this->app->make('db');

    $connection = $connection ?: $database->getDefaultConnection();

    $count = $database->connection($connection)->table($table)->where($data)->count();

    $this->assertGreaterThan(0, $count, sprintf(
        'Unable to find row in database table [%s] that matched attributes [%s].', $table, json_encode($data)
    ));

    return $this;
}

As you can see, the where function works as it would normally without any data escaping. I would suggest adding a custom method in the trait that would deal with edge cases like yours. For example:

protected function seeResponseInDatabase($table, $response, $connection = null)
{
    $database = $this->app->make('db');

    $connection = $connection ?: $database->getDefaultConnection();

    $count = $database->connection($connection)->table($table)->where('response','like', '%' . $response . '%')->count();

    $this->assertGreaterThan(0, $count, sprintf(
        'Unable to find row in database table [%s] that matched attributes [%s].', $table, $response
    ));

    return $this;
}

So, instead of passing the array, just pass your expected response. Instead of going on this route first, I would actually dd the $data array of the seeInDatabase method just to make sure the data is passed to the where clause as intended.

Hope this gives you some idea to resolve your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM