I would just add a $this->assertException(\Illuminate\Auth\Access\AuthorizationException::class); to your test and be done with it.
Aug 13, 2023
8
Level 63
Livewire 3 - assetUnauthorized() doesn't work
Hello,
I have written a test to check that a user cannot create a category.
/** @test */
public function user_cannot_create_a_category(): void
{
$user = User::factory()->create();
$this->assertEquals(0, Category::count());
Livewire::
actingAs($user)
->test(Categories::class)
->set('form.name', 'Une catégorie')
->call('save')
->assertUnauthorized();
$this->assertEquals(0, Category::count());
}
The test is aborted and I get this error.
Illuminate\Auth\Access\AuthorizationException: This action is unauthorized.
Wheras when I check that an admin can create a category, it works fine.
I specify that I have checked the authorization in the Livewire controller inside the save() method.
Categories component
public function save()
{
$this->form->save();
$this->showModal = false;
}
CategoryForm
public function save()
{
if ($this->id) {
$this->update();
} else {
$this->store();
}
$this->reset();
}
public function store()
{
$this->authorize('create', Category::class);
$this->cleanFields();
$validated = $this->validate();
$category = new Category;
$category->fill($validated);
$category->save();
}
Is it a bug or do I have forgotten something ?
Thanks for your help.
V
Level 37
@vincent15000 I understand where it's happening but if you add the expectException() to the top of the test, it won't die there and will instead just move on to the next line (assertUnauthorized())
1 like
Please or to participate in this conversation.