angularjslaravelphpunitlaravel-3

Testing laravel controllers with JSON request body


I am trying to write a phpunit test for a Laravel controller which expects post requests with a body in JSON format.

A simplified version of the controller:

class Account_Controller extends Base_Controller
{
    public $restful = true;

    public function post_login()
    {
        $credentials = Input::json();
        return json_encode(array(
            'email' => $credentials->email,
            'session' => 'random_session_key'
        ));
    }
}

Currently I have a test method which is correctly sending the data as urlencoded form data, but I cannot work out how to send the data as JSON.

My test method (I used the github gist here when writing the test)

class AccountControllerTest extends PHPUnit_Framework_TestCase {
    public function testLogin()
    {
        $post_data = array(
            'email' => 'user@example.com',
            'password' => 'example_password'
        );
        Request::foundation()->server->set('REQUEST_METHOD', 'POST');
        Request::foundation()->request->add($post_data);
        $response = Controller::call('account@login', $post_data);
        //check the $response
    }
}

I am using angularjs on the frontend and by default, requests sent to the server are in JSON format. I would prefer not to change this to send a urlencoded form.

Does anyone know how I could write a test method which provides the controller with a JSON encoded body?


Solution

  • There is a lot easier way of doing this. You can simply set Input::$json property to the object you want to send as post parameter. See Sample code below

     $data = array(
            'name' => 'sample name',
            'email' => 'abc@yahoo.com',
     );
    
     Input::$json = (object)$data;
    
     Request::setMethod('POST');
     $response = Controller::call('client@create');
     $this->assertNotNull($response);
     $this->assertEquals(200, $response->status());
    

    I hope this helps you with your test cases

    Update : The original article is available here http://forums.laravel.io/viewtopic.php?id=2521