Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test POST routes in Laravel

I'm doing the following to test a POST call to Laravel. I'm expecting that POST to questions, in accordance with my routes, will be dispatches as the store action method. This works in the browser.

My test:

public function setUp()
    {   
        parent::setUp();

        Session::start();
    }

    public function testStoreAction()
    {
        $response = $this->call('POST', 'questions', array(
            '_token' => csrf_token(),
        ));

        $this->assertRedirectedTo('questions');
    }

However, I tells me that the redirect doesn't match. Also, I can see that it isn't going to the store action method at all. I want to know what action method it is going to, and why it isn't going to the store method (if I look at route:list I can see there is a POST questions/ route that should go to questions.store; this also works in the browser, but not in my tests). Also, am I writing the call correctly for this resource? I added the token here as it was throwing an exception as it should, in some tests I will let the token check pass.

like image 216
Martyn Avatar asked Mar 01 '15 05:03

Martyn


People also ask

How can I get current route in Laravel?

Accessing The Current RouteThe Route::current() method will return the route handling the current HTTP request, allowing you to inspect the full Illuminate\Routing\Route instance: $route = Route::current(); $name = $route->getName();

What is PHPUnit Laravel?

Use Laravel Unit Testing to Avoid Project-Wrecking Mistakes. Pardeep Kumar. 7 Min Read. PHPUnit is one of the most well known and highly optimized unit testing packages of PHP. It is a top choice of many developers for rectifying different developmental loopholes of the application.

How do I run a test case in PHP?

From the Menu-bar, select Run | Run As | PHPUnit Test . To debug the PHPUnit Test Case, click the arrow next to the debug button on the toolbar, and select Debug As | PHPUnit Test . From the Main Menu, select Run | Debug As | PHPUnit Test . The unit test will be run and a PHP Unit view will open.


2 Answers

You could try this:

public function testStoreAction()
{
    Session::start();
    $response = $this->call('POST', 'questions', array(
        '_token' => csrf_token(),
    ));
    $this->assertEquals(302, $response->getStatusCode());
    $this->assertRedirectedTo('questions');
}
like image 198
Daniel Ojeda Avatar answered Oct 20 '22 13:10

Daniel Ojeda


The most recommended way to test your routes is to check for 200 response. This is very helpful when you have multiple tests, like you are checking all of your post routes at once.

To do so, just use:

public function testStoreAction()
{
    $response = $this->call('POST', 'questions', array(
        '_token' => csrf_token(),
    ));

    $this->assertEquals(200, $response->getStatusCode());
}
like image 30
Raviraj Chauhan Avatar answered Oct 20 '22 11:10

Raviraj Chauhan