Vince
Vince

Reputation: 1664

Phpunit testing Laravel 5.1 restful controller

I have been stuck on that issue for a little while, no other question on SO helped me.

I am using Laravel 5.1 and phpunit to test a restful controller. My testing code looks as such:

$this->post('/api/book', [ 'title' => 'my book'])
  ->assertResponseOk();

And the target controller has, among others, the following code:

Log::debug('title: ' . $request->json('title'));

i.e. on the testing side I expect to use the TestCase::post() method to send a request and on the server side I expect to use the Request::json() method to read from the request. However when I look at the logs I see the following empty string

[2015-10-31 17:26:01] testing.DEBUG: title:   

This is showing that either my testing code is not setting the right data in the request or that my server code is not reading the request properly. By the way, the server is failing a bit further as well, reflecting the missing title value in the logs.

I am also using a Firefox plugin, RESTClient, to manually test my web app and I had to set properly the body (using double-quotes around the title key, respecting strictly the JSON specs) to make sure the server code work. So the exact format is a trail I followed, without success so far.

So my question is, what is the most recommended code to use for a RESTful controller on the testing and on the server sides, in Laravel 5.1?

Upvotes: 1

Views: 332

Answers (1)

David Wickström
David Wickström

Reputation: 397

The reason your log is empty is because this call $request->json('title') actually returns an array, not a string.

https://github.com/illuminate/http/blob/master/Request.php#L552

The correct way of accessing the key is like so:

Log::debug('title: ' . $request->title);

As described here:

http://laravel.com/docs/5.1/requests#retrieving-input

Upvotes: 1

Related Questions