Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Laravel Input::replace() in testing POST requests

I'm having some trouble using Laravel's Input::replace() method to simulate a POST request during unit testing.

According to Jeffrey Way here and here, you can do something like this:

# app/tests/controllers/PostsControllerTest.php

public function testStore()
{
    Input::replace($input = ['title' => 'My Title']);</p>

    $this->mock
         ->shouldReceive('create')
         ->once()
         ->with($input);

    $this->app->instance('Post', $this->mock);

    $this->call('POST', 'posts');

    $this->assertRedirectedToRoute('posts.index');
}

However, I can't get this to work. Input::all() and all Input::get() calls still return an empty array or null after Input::replace() is used.

This is my test function:

public function test_invalid_login()
{
    // Make login attempt with invalid credentials
    Input::replace($input = [
        'email'     => '[email protected]',
        'password'  => 'badpassword',
        'remember'  => true
    ]);

    $this->mock->shouldReceive('logAttempt')
    ->once()
    ->with($input)
    ->andReturn(false);

    $this->action('POST', 'SessionsController@postLogin');

    // Should redirect back to login form with old input
    $this->assertHasOldInput();
    $this->assertRedirectedToAction('SessionsController@getLogin');
}

The $this->mock->shouldReceive() doesn't get called with $input though - it only gets an empty array. I've confirmed this in the debugger by looking at Input::all() and Input::get() for each value, and they're all empty.

TL/DR: How do I send a request with POST data in a Laravel unit test?

like image 545
glasstree Avatar asked Jun 05 '14 02:06

glasstree


1 Answers

You should use Request::replace(), not Input::replace in order to replace input data for the current request.

like image 197
Vladislav Rastrusny Avatar answered Sep 28 '22 00:09

Vladislav Rastrusny