Brad Koch
Brad Koch

Reputation: 20297

Setting headers for CakePHP Controller unit tests

I'm writing some unit tests for a Controller in which the response behavior differs slightly, depending on whether $this->request->is('ajax'). I've been looking over the documentation for testing controllers, but I can't seem to find a way to simulate a request made via AJAX.

Is there a way to send headers to testAction() so I can set the X-Requested-With header?

Edit: You can work around this by editing the superglobals. Anyone have a less hacky solution?

Upvotes: 1

Views: 1415

Answers (1)

Brad Koch
Brad Koch

Reputation: 20297

One solution is to manually declare the necessary environment variable for the duration of your test:

$_ENV['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
// Run your AJAX test...
unset($_ENV['HTTP_X_REQUESTED_WITH']);

Upvotes: 2

Related Questions