Home>

I wrote it in the controller in Laravel. I'm writing a unit test for a method called addStaffDate.
The program looks like this:

StaffDate.php

  public static function addStaffDate(array $arr)
    {
        $time = Carbon::now();
        $staff_date = new StaffDate();
        foreach ($arr['id'] as $id) {
            $staff_date->create([
                'Staff_id' =>$id,
                'time' =>$time,
            ]);
        };
    }

StaffDateTest.php

  public function testStaffDate()
    {
        $data = [
            'id'=>[1],
        ];
        StaffDate::addStaffDate($data);
        $time = Carbon::now();
        $this->assertDatabaseHas('staff_date', [
            'Staff_id' =>1,
            'time' =>$time,
        ]);
    }

The unit test failed, but the cause of the error seems to be a difference in the display of Carbon::now().

Looking at the error message,

"Staff_id": 1
"time": "2020-09-04T11:08:10.842939Z",

The value of is output, and the value found in DB is

"Staff_id": 1
"time": "2020-09-04 20:08:10",

was. Perhaps before the value is saved in the database, it is displayed in UTC display time and fine seconds, and the time zone such as T or Z? I think this is because the character "" is also output.

I would like to format the date in the unit test description, but I don't know how to do it.

StaffDateTest.php

  public function testStaffDate()
    {
        $data = [
            'id'=>[1],
        ];
        StaffDate::addStaffDate($data);
        $time->format("2020-09-04T11:08:10.842939Z");
        $this->assertDatabaseHas('staff_date', [
            'Staff_id' =>1,
‘Time’ =>$time,
        ]);
    }

How would you describe the following part and it would work?

$time->format("2020-09-04T11:08:10.842939Z);
  • Answer # 1

    https://qiita.com/pinkumohikan/items/2e9cefb85d75a8622d99

    It's better to look at config first.

  • Answer # 2

    StaffDateTest.php

    $time = Carbon::now();

    To

    $time = Carbon::now()->format('Y-m-d H:i:s');

    I rewritten it to
    Thank you for the advice.