@Shivangi58 this is wrong though; why do you create a Treatment before sending the Request; now there is a database record already? The problem with the $treatment variable is the User that it is associated with; which is not the authenticated user; it is another User created by the Factory.
All you care about is the raw values which would represent the JSON payload sent in the Request; you can get these from the Factory methods, make (Object) or raw (Array) - since you don't really need an Object; I am using the Array result below:
protected $user;
public function setUp():void
{
parent::setUp();
$this->user = User::factory()->create();
Sanctum::actingAs($user);
// ...
}
Now, use $this->user in the assertions about which User is associated:
public function store_treatment()
{
$treatment = Treatment::factory()->raw();
$response = $this->postJson(route('treatments.store'), [
'title' => $treatment['title'],
'notes' => $treatment['notes'],
'start_date' => $treatment['start_date'],
'end_date' => $treatment['end_date'],
'start_time' => $treatment['start_time'],
'end_time' => $treatment['end_time'],
])
->assertCreated()
->json();
$this->assertEquals($treatment['title'], $response['title']);
$this->assertEquals($treatment['notes'], $response['notes']);
$this->assertEquals($this->user->id, $response['patient_id']);
$this->assertEquals($treatment['start_date'], $response['start_date']);
$this->assertEquals($treatment['end_date'], $response['end_date']);
$this->assertEquals($treatment['start_time'], $response['start_time']);
$this->assertEquals($treatment['end_time'], $response['end_time']);
$this->assertDatabaseHas('treatments', [
'title' => $treatment['title'],
'notes' => $treatment['notes'],
'patient_id' => $this->user->id,
'start_date' => $treatment['start_date'],
'end_date' => $treatment['end_date'],
'start_time' => $treatment['start_time'],
'end_time' => $treatment['end_time'],
]);
}
So in summary, your test is asserting
- that you get a
201 response to the POST request
- that the response JSON contains all of the values you specify (incl. the
patient_id which was not in the original Request payload)
- that there is a database record with the specified values (incl. the
patient_id which matches the authenticated user)