Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling named routes in laravel tests

consider the following:

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class HomeRouteTest extends TestCase
{
    public function testVisitTheHomePage()
    {
        $response = $this->call('GET', '/');
        $this->assertEquals(200, $response->status());

    }

    public function testVisitTheAboutPage()
    {
        $response = $this->call('GET', '/about');
        $this->assertEquals(200, $response->status());
    }
}

Is there away, not that I have seen documented >.>, to do something like:

$response = $this->call('GET', 'home.about');
$this->assertEquals(200, $response->status());

Or .... Is that how you do it?

The error I get is:

vagrant@scotchbox:/var/www$ phpunit
PHPUnit 4.8.21 by Sebastian Bergmann and contributors.

FF

Time: 3.41 seconds, Memory: 14.25Mb

There were 2 failures:

1) HomeRouteTest::testVisitTheHomePage
Failed asserting that 404 matches expected 200.

/var/www/tests/HomeRouteTest.php:12

2) HomeRouteTest::testVisitTheAboutPage
Failed asserting that 404 matches expected 200.

/var/www/tests/HomeRouteTest.php:19

FAILURES!
Tests: 2, Assertions: 2, Failures: 2.
like image 439
TheWebs Avatar asked Jan 03 '16 21:01

TheWebs


People also ask

How can I get route name in Laravel?

You may use the current, currentRouteName, and currentRouteAction methods on the Route facade to access information about the route handling the incoming request: $route = Route::current(); $name = Route::currentRouteName(); $action = Route::currentRouteAction();

Why we use named routes in Laravel?

Named routing is another amazing feature of Laravel framework. Named routes allow referring to routes when generating redirects or Urls more comfortably. You can specify named routes by chaining the name method onto the route definition: Route::get('user/profile', function () { // })->name('profile');

What is named routing in Laravel?

Named routes is an important feature in the Laravel framework. It allows you to refer to the routes when generating URLs or redirects to the specific routes. In short, we can say that the naming route is the way of providing a nickname to the route.


1 Answers

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.

like image 82
Miguel Arias Avatar answered Oct 29 '22 09:10

Miguel Arias