PHPUnit: Testing Form Validity with CSRF Hash in Controller Actions - Another Zend 2 Snippet

I needed to test code inside a form's isValid() call, inside a Zend Framework 2 controller action. This is effectively hard-coded. Stubbing didn't seem to be the answer, and a little googling didn't throw up much. The work around is actually really simple.

All forms I'm testing make use of (Zend's own) csrf hash which must be parsed to validate the form. Thankfully this is stored in the session; it just needs to be created before you call a dispatch, assuming you're using or extending Zend's base From class, like so:


public function testForm()
{
    $form = new \Module\Forms\MyForm();
    $form->prepare();

The csrf token has now been created and stored to the session, and can be added to the array of POST variables.
    $this->setMethod('POST');
    $this->setPost(
               new \Zend\Stdlib\Parameters(
            array(
   'csrf' => $form->get('csrf')->getValue(), 
   'element1' => 'value', 
   'element2' => 'value')
   )
  );
    $this->controller->dispatch($this->request);

    // some test

}

The csrf has is stored in
$_SESSION['Zend_Validator_Csrf_salt_csrf']['hash']
but is easier to pull from the form itself.
I have this running in a bunch of tests and it works fine without a lot of mucking about.

Comments

Post a Comment

Popular Posts