But I need the same user so he can update the category that was previously created by him. Another user can't update the category he just created.
@alberto98 Nope. The test should be separate. You shouldn’t be using state from one test case in another.
If you want to test a user can update a category they’ve created, and also test they can’t update categories created by another users, then create test cases for those and use database factories to create the relevant models:
public function testUserCanUpdateTheirOwnCategories(): void
{
$user = User::factory()->create();
$category = Category::factory()->for($user)->create();
$this
->actingAs($user, 'sanctum')
->patch("/api/categories/{$id}", [
'name' => 'Test update category',
'description' => 'This is an updated description',
])
->assertOk()
->assertJson(['status' => 'success']);
// Assert category was updated in database
$this->assertDatabaseHas('categories', [
'id' => $category->getKey(),
'name' => 'Test update category',
'description' => 'This is an updated description',
]);
}
public function testUserCannotUpdateCategoryCreatedByAnotherUser(): void
{
$user = User::factory()->create();
$otherUser = User::factory()->create();
$category = Category::factory()->for($otherUser)->create();
$this
->actingAs($user, 'sanctum')
->patch("/api/categories/{$id}", [
'name' => 'Test update category',
'description' => 'This is an updated description',
])
->assertForbidden();
// Assert category was not updated in database
$this->assertDatabaseMissing('categories', [
'id' => $category->getKey(),
'name' => 'Test update category',
'description' => 'This is an updated description',
]);
}
Also, status => success in your JSON response is completely redundant as you should be using the appropriate HTTP status codes to designate whether a request was “successful” or not.