Calling named routes in laravel tests

This solution works for any Laravel 5 version to my knowledge. Especially Laravel 5.4+ unlike the other solution mentioned here.

If your named route has parameters, you can just do this:

$response = $this->get(route('users.show', [
    'user' => 3,
]));

$response->assertStatus(200);

If your named route has no parameters then you can just do this:

$response = $this->get(route('users.index'));

$response->assertStatus(200);

Nice and simple.


This is a very late response, but I think what you're looking for is:

$this->route('GET', 'home.about');
$this->assertResponseOk(); // Checks that response status was 200

For routes with parameters, you can do this:

$this->route('GET', 'users.show', ['id' => 3]); // (goes to '/users/3')

I needed this to test some ghastly routes I'm working with, which look like this:

Route::resource(
    '/accounts/{account_id}/users',
    'AccountsController@users',
    [
        'parameters' => ['account_id'],
        'names'      => [
            'create'  => 'users.create',
            'destroy' => 'users.destroy',
            'edit'    => 'users.edit',
            'show '   => 'users.show',
            'store'   => 'users.store',
            'update'  => 'users.update',
        ]
    ]
);

To make sure that my routes and redirects went to the right page I did this:

/**
 * @test
 */
public function users_index_route_loads_correct_page()
{
    $account = Account::first();

    $response = $this->route('get', 'users.index', ['account_id' => $account->id]);
    $this->assertResponseOk()
        ->seePageIs('/accounts/' . $account->id . '/users');
}

To make sure I was using the right view file (we all make copy-paste errors, right?), I did this:

/**
 * @test
 */
public function users_index_route_uses_expected_view()
{
    $account = Account::first();

    $response = $this->route('get', 'users.index', ['account_id' => $account->id]);

    $view = $response->original; // returns View instance
    $view_name = $view->getName();

    $this->assertEquals($view_name, 'users.index'); 
}

If it weren't for the Structure feature in PHPStorm and the documentation from Laravel 4.2 that I stumbled over, I don't think I would have ever figured out how to test those routes. I hope this saves someone else a bit of time.