vincent15000's avatar

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

0 likes
8 replies
nexxai's avatar

I would just add a $this->assertException(\Illuminate\Auth\Access\AuthorizationException::class); to your test and be done with it.

1 like
vincent15000's avatar

@nexxai Yes but isn't it the role of $this->assertUnauthorized(); ?

I just tested your suggestion and it doesn't work better.

I specify that I get the same error if I remove the ->assertUnauthorized().

vincent15000's avatar

@nexxai I specify that the error occurs here.

Livewire::
    actingAs($user)
    ->test(Categories::class)
    ->set('form.name', 'Une catégorie')
    ->call('save') // the error occurs here
    ->assertUnauthorized(); // this line is not executed
vincent15000's avatar

@nexxai According to the Livewire documentation, it should work. I wonder if it's a bug ;).

nexxai's avatar
nexxai
Best Answer
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
vincent15000's avatar

@nexxai Yes thank you now it works fine.

I wonder why $this->withoutExceptionHandling() doesn't work.

Please or to participate in this conversation.