browntown's avatar

Why does assertRedirectToRoute fail if I pass a parameter?

I'm curious why my tests are failing. assertRedirectToRoute fails if I use it with a route that has a parameter in it. The test passes if the redirected route does not have a parameter.

My test will pass if I use the assertRedirect() and and the url to the route directly.

The route looks like this:

Route::get('/projects/{project_id}', [ProjectController::class, 'show'])->name('project');

For example:

This test will fail.

test('can add section to project', function () {
    $user = User::factory()->create();
    $project = Project::factory()->create();
    $response = $this->actingAs($user)->post('/section/add', ['user_id'=>$user->id, 'project_id'=>$project->id, 'name'=>fake()->name()]);

    $response->assertRedirectToRoute('project' [$project->id]);
});

This test will pass.

test('can add section to project', function () {
    $user = User::factory()->create();
    $project = Project::factory()->create();
    $response = $this->actingAs($user)->post('/section/add', ['user_id'=>$user->id, 'project_id'=>$project->id, 'name'=>fake()->name()]);

    $response->assertRedirect('/projects/'.$project->id);
});

I'm fine modifying my tests to use assertRedirect instead of assertRedirectToRoute, was just curious why the assertRedirectToRoute with a param fails. I didn't see anything in the documentation indicating it would.

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The issue you're encountering with assertRedirectToRoute is likely due to the way parameters are being passed to the method. In Laravel, when you use assertRedirectToRoute, you need to pass the route name and an associative array of parameters. The syntax you're using seems to be missing a comma between the route name and the parameters array.

Here's how you can modify your test to use assertRedirectToRoute correctly:

test('can add section to project', function () {
    $user = User::factory()->create();
    $project = Project::factory()->create();
    $response = $this->actingAs($user)->post('/section/add', [
        'user_id' => $user->id,
        'project_id' => $project->id,
        'name' => fake()->name()
    ]);

    $response->assertRedirectToRoute('project', ['project_id' => $project->id]);
});

In this corrected version, note the comma after 'project' and the use of an associative array ['project_id' => $project->id] to pass the route parameters. This should resolve the issue and allow your test to pass using assertRedirectToRoute.

1 like
browntown's avatar

Oh wow. This is embarrassing. It took me asking a question to realize I missed a comma as the AI rightly recognized. Plus 1 for the robots.

$response->assertRedirectToRoute('project' [$project->id]);

Should have been

$response->assertRedirectToRoute('project', [$project->id]);

Please or to participate in this conversation.