John Davidson

php - PHPUnit assertDatabaseHas with Laravel and Inertia

0 comments
Message:


I have a Laravel 8 setup that utilises Intertia.js. I'm trying to test my post routes to store new resources and want to assert that the database has the new record stored, using the assertDatabaseHas() method.


Controller.php


public function store(SlotCreate $request): RedirectResponse
{
$slot = CreateSlot::dispatchNow($request);

return redirect()->back()->with([
'message' => 'Slot Created Successfully.',
'slot' => new SlotResource($slot)
]);
}

CreateSlotTest.php


public function testCreateSlot()
{
$response = $this->actingAs($this->teamAdminOne)->post('/slots', [
'start_time' => '09:00',
'end_time' => '10:00',
'max_bookings' => 3
]);

$response->assertStatus(302);

$this->assertDatabaseHas('slots', [
'id' => ???
'team_id' => $this->teamAdminOne->currentTeam(),
'start_time' => '09:00',
'end_time' => '10:00',
'max_bookings' => 3
]);
}

When I debug the session I can see the slot that I added to the with() method but I can't figure out how to access it.


I'd like to know if I'm returning the slot correctly in the controller and if yes, how do I access the response to assert if the database has this record?



My Answer:
In your controller, you are returning the slot as part of the 'slot' key in the with() method. To access this slot in your test, you can retrieve it from the response object using the session() method.

Here's how you can modify your test to access the slot from the response and then use it to assert the database has the new record:

php
public function testCreateSlot()
{
$response = $this->actingAs($this->teamAdminOne)->post('/slots', [
'start_time' => '09:00',
'end_time' => '10:00',
'max_bookings' => 3
]);

$response->assertStatus(302);

$slot = $response->session()->get('slot');

$this->assertDatabaseHas('slots', [
'id' => $slot['id'],
'team_id' => $this->teamAdminOne->currentTeam(),
'start_time' => '09:00',
'end_time' => '10:00',
'max_bookings' => 3
]);
}


In this modified test, we retrieve the slot from the response using $response->session()->get('slot') and then use the 'id' from the slot to assert that the database has the new record.

Make sure that the 'id' field in the database matches the 'id' of the slot returned in the response. If the 'id' is auto-generated by the database, you may need to retrieve it from the database after the record is created and use it in the assertDatabaseHas() method.

This should help you access the slot returned in the controller and assert that the database has the new record stored.

Rate this post

4 of 5 based on 1249 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us