Reputation: 55
I try to setup a Json Response View in CakePHP. I read several times the docs https://book.cakephp.org/4/en/views/json-and-xml-views.html but i cannot find a solution to return a specific response code.
So that is currently my code
$customers = $this->Customers->find('all')->where(['organisation_id' =>1] )->contain($this->contain)->toArray();
$this->set('customers', $customers);
$this->viewBuilder()->setOption('serialize', 'customers');
$this->viewBuilder()->setClassName('Json');
I know i can return a json and a response code with this
return $this->response->withStatus(400)->withType('json')->withStringBody(json_encode($customers));
But with this code you cannot write tests for it. I hope anyone have a solution for this.
Upvotes: 0
Views: 1045
Reputation: 3327
You definitely can test for that custom code and body, ex.:
$this->get('/customers/yourfunction.json');
$this->assertResponseCode(400); // Check for the custom response code
$this->assertResponseContains('{"customers":'); // Checks for the start of the JSON body, but you can check the response body is as expected any number of ways
Upvotes: 0
Reputation: 60463
I don't see why it shouldn't be possible to write tests for the latter variant. Your tests shouldn't care about implementation details, they should just test the response that the request returns.
That being said, you can configure responses without having to return them from the controller, just set them back on the controller's property:
$this->response = $this->response->withStatus(400);
Upvotes: 1