i\'m currently testing an app that simply searches a record by the given id. It works fine but the testing refuses to return the response in the code. Strangely it is ONLY s
Controller actions are not supposed to echo data, even though it might work in some, maybe even most situations. The correct way of outputting data that doesn't stem from a rendered view template, is to configure and return the response object, or to use serialized views.
The test environment relies on doing this properly, as it doesn't buffer possible output, but will use the actual value returned from the controller action.
The following is basically a copy from https://stackoverflow.com/a/42379581/1392379
Quote from the docs:
Controller actions generally use
Controller::set()
to create a context that View uses to render the view layer. Because of the conventions that CakePHP uses, you don’t need to create and render the view manually. Instead, once a controller action has completed, CakePHP will handle rendering and delivering the View.If for some reason you’d like to skip the default behavior, you can return a
Cake\Network\Response
object from the action with the fully created response.
* As of 3.4 that would be \Cake\Http\Response
Cookbook > Controllers > Controller Actions
$content = json_encode($comuna);
$this->response->getBody()->write($content);
$this->response = $this->response->withType('json');
// ...
return $this->response;
The PSR-7 compliant interface uses immutable methods, hence the utilization of the return value of withType()
. Unlike setting headers and stuff, altering the body by writing to an existing stream doesn't change the state of the response object.
CakePHP 3.4.3 will add an immutable withStringBody
method that can be used alternatively to writing to an existing stream.
$this->response = $this->response->withStringBody($content);
$content = json_encode($comuna);
$this->response->body($content);
$this->response->type('json');
// ...
return $this->response;
$content = json_encode($comuna);
$this->set('content', $content);
$this->set('_serialize', 'content');
This requires to also use the request handler component, and to enable extensing parsing and using correponsing URLs with .json
appended, or to send a proper request with a application/json
accept header.