We can use AjaxContext action helper to define a context of an action.
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('get-zip-code', 'json')
->initContext();
}
public function getZipCodeAction()
{
// that is all! you don't need to do any for json encode
$this->view->zip = '123';
}
Since we use AjaxContext then we don’t need to create a get-zip-code.phtml.
Till this step everything is fine.
Then I want to write a unit test for it.
class ZipControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
public function setUp()
{
$this->bootstrap = new Zend_Application(
APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
parent::setUp();
}
/**
* testICanGetZipCodeAsJsonString
*
* @return void
* @group now
*/
public function testICanGetHashForCheckingCredit()
{
$this->dispatch(
'/checkout/payone/get-hash-for-checking-credit/format/json');
$this->assertResponseCode(200);
$this->assertEquals('{"zip":"123"}', $this->getResponse()->getBody());
}
}
The second assertion fails. And using var_dump($this->getResponse()->getBody()) we can find out the layout is not disable. Why? Doesn’t AjaxContext work? After a little hacking the Zend_Controller_Action_Helper_AjaxContext I found the AjaxContext will chech the type of Request. It works just when the Request is a Xml Http Request.
In order let test to work, we have to forge the Request before dispatch it.
/**
* testICanGetZipCodeAsJsonString
*
* @return void
* @group now
*/
public function testICanGetHashForCheckingCredit()
{
// forge the request as an XMLHttpRequest!
$this->getRequest()->setHeaders(array('X_REQUESTED_WITH' => 'XMLHttpRequest'));
$this->dispatch(
'/checkout/payone/get-hash-for-checking-credit/format/json');
$this->assertResponseCode(200);
$this->assertEquals('{"zip":"123"}', $this->getResponse()->getBody());
}
Now the test working fine.