codeninja.sj
codeninja.sj

Reputation: 4119

How to test Zend framework2 form which implements CSRF element?

I have created the login form using Zend/Form and it contains input elements as well as CSRF element.

<!-- sample login.phtml code snippet -->
<form method="post" action="/xyz">
<?php
 echo $this->formelement($form->get('email'));
 echo $this->formelement($form->get('password'));
 echo $this->formelement($form->get('csrf'));
 echo $this->formelement($form->get('submit'));
?>
</form>

The following testcase fails because of the validation against CSRF element.

public function testLogin()
{      
  //code goes here
  $params = array('email' => '[email protected]', 'password' => '[email protected]');
  $this->dispatch($url, $method, $params);
  //if the given username and password is correct the login page redirected to default home page
  $this->assertResponseStatusCode(302);
}

In the above testcase i set the email and password values but i don't know how to set CSRF element. How could i test the form which implements CSRF element?

Upvotes: 0

Views: 174

Answers (1)

Purple Hexagon
Purple Hexagon

Reputation: 3578

This can easily be achieved with the following:

    $form = new LoginForm();
    $csrf = $form->get('csrf')->getValue();
    $params = array('email' => '[email protected]', 
                    'password' => '[email protected]', 
                    'csrf' => $csrf
    );

Unless your form needs the form manager when you are going to have to use that rather than just instantiating the class but that's pretty easy to do in a unit test as well.

UPDATE:

Another method that works:

    $form = new LoginForm();
    $form->prepare();

    $params = new \Zend\Stdlib\Parameters(
                    array(
                            'csrf' => $_SESSION['Zend_Validator_Csrf_salt_csrf']['hash'],
                            'yourotherparams' => 'thingsandstuff'
            );


    $this->dispatch($url, $method, $params);

Upvotes: 1

Related Questions