0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LaravelのユニットテストでDBにないエラーを明確にする

Last updated at Posted at 2021-01-05

Problem

When seeInDatabase asserting was failed, I can’t not known where the path of properies is not match.

Example: With bellow test, I will receive the bellow message.

Test code:
    $this->seeInDatabase('les_knowledge', [
        'lesson_id' => $lesson->id,
        'number' => 1,
        'content_en' => '~ years old DIFFFFFFFFFF',
        'explanation_en' => 'In Japan, you are born as a 0 year-old and turn 1 on your first birthday.',
    ]);
Test result:
Unable to find row in database table [les_knowledge] that matched attributes
    [{
        "lesson_id":98,"number":1,
        "content_en":"~ years old DIFFFFFFFFFF",
        "explanation_en":"In Japan, you are born as a 0 year-old and turn 1 on your first birthday."
    }]

It is hard to find where is the path don’t match.

Solution

Create a function likes a bellow.

    function seeInDatabaseAndHasProperties($table, array $filter, array $properties, $connection = null){
        $this->seeInDatabase($table, $filter, $connection);
        $model = (array)DB::table($table)->where($filter)->first();
        $this->assertEquals($properties, Arr::only($model, array_keys($properties)));
    }
Test code will be:
    $this->seeInDatabaseAndHasProperties('les_knowledge',
    [
        'lesson_id' => $lesson->id,
        'number' => 1,
    ], [
        'content_en' => '~ years old DIFFFFFFFFFF',
        'explanation_en' => 'In Japan, you are born as a 0 year-old and turn 1 on your first birthday.',
    ]);
Test result will be:
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
    -    'content_en' => '~ years old DIFFFFFFFFFF'
    +    'content_en' => '~ years old'
    'explanation_en' => 'In Japan, you are born as a 0...thday.'
)

Now you can easily see which properties don’t match.
Original post is: https://khoinv.com/post/639359603705020416/clear-errors-not-found-in-the-database-laravel

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?