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?
You should use Request::replace(), not Input::replace in order to replace input data for the current request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With