Home > other >  Laravel Testing assertRedirect for unauthenticated user
Laravel Testing assertRedirect for unauthenticated user

Time:10-04

I write here after many attempts but my problem isn't solved yet.

I want to create a test using PHPUnit on Laravel my class has function described like below:

public function test_not_connected_user_can_not_create_new_task() {
            
    $this->withoutExceptionHandling();

    //Given we have a task object
    $task = Task::factory()->make();

    // When unauthenticated user submits post request to create task endpoint
    // He should be redirected to login page
    $this->post('/tasks/store',$task->toArray())
        ->assertRedirect(route('login'));
}

Here is my route:

Route::post('/tasks/store', [App\Http\Controllers\TaskController::class, 'store'])
    ->name('store');

And my controller functions:

public function __construct() {
    $this->middleware('auth')->except(['index','show']);
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request) {
    $task = Task::create([
        'title' => $request->get('title'),
        'description' => $request->get('description'),
        'user_id' => Auth::id()
    ]);

    return redirect()->route('show', [$task->id]);
}

We have a middleware here to manage authentication.

When I run the test:

vendor/bin/phpunit --filter test_connected_user_can_create_new_task

I get this error:

  1. Tests\Feature\TasksTest::test_not_connected_user_can_not_create_new_task Illuminate\Auth\AuthenticationException: Unauthenticated.

And it's pointing to this line:

$this->post('/tasks/store', $task->toArray())

The expected behavior is that it should redirect to login but here the test fail and I can't see why.

Thanks

CodePudding user response:

The issue is super easy to fix. You have $this->withoutExceptionHandling(); and that is literally throwing the error, what you want is to catch it and let everything continue. To do so, remove that line of code and your test will work.

  • Related