Testing Multi Step Forms In Drupal 7

14th June 2012

I am currently using SimpleTest to test a complex multi-step form implementation in Drupal 7. It made sense to do it this way as there are a lot of factors involved that all need to be accounted for and automating what form elements appeared on what page was the most robust solution. In order to test how the form worked I needed to submit to the form once (using a $this->drupalPost() method) and then submit the form again using the same method. The tricky bit here was that when calling the drupalPost() method with a URL it first called drupalGet() on the URL before posting to the form. This basically meant that the form was initiated twice and never got past the second page.

The solution to this was pretty straightforward, but it took me a while to find it. Essentially, to stop the drupalPost() method from running drupalGet() first just supply the URL paramter (the first parameter) of drupalPost() as NULL. This skips the reloading of the form and posts the form state back to the form. Here is the code that will test the first two stages of a multistep form, I have left out the rest of the DrupalWebTestCase class.

  1. // post to first step of multistep form
  2. $this->drupalPost('first/step/in/multistep/form', array(), 'Next');
  3.  
  4. // do assertions
  5. // Form element exists on second page of form.
  6. $this->assertFieldByName('form_element', '');
  7.  
  8. // second step
  9. $input = array(
  10. 'form_element' => 'form_value',
  11. );
  12.  
  13. $this->drupalPost(NULL, $input, 'Next');
  14.  
  15. // second step assertions

This method can also be used to run repeated submissions to a form when testing form validation.

Add new comment

The content of this field is kept private and will not be shown publicly.