Module Development

Testing and Submitting Forms with SimpleTest for Drupal 7

This page is archived

We're keeping this page up as a courtesy to folks who may need to refer to old instructions. We don't plan to update this page.

Alternate resources

Sprout Video

Much of the functionality that web based applications provide is in the form of an HTML form. Enter some data into the various fields, press the submit button, and see what happens. The DrupalWebTestCase provides a handful of methods to aid in interacting with forms. In this lesson we'll take a look at filling out various types of form fields, submitting forms, and validating the result.

We'll start by navigating to a page that contains a form and simply verifying that the appropriate fields are found on the page.


$this->drupalGet('helloworld/form');
$this->assertFieldByXpath("//form[@id='helloworld-cake-form']//input[@name='name']", '', 'The name field is present.');
$this->assertFieldByName('choice', 'cake', 'The choice field is present.');

This code checks for the input name="name" field, and the select name="choice" field, and ensures they are present on the page at hellworld/form.

Then we'll use the DrupalWebTestCase::drupalPost() method to fill in, and submit, a form. Here's an example:


$data = array(
  'name' => '',
  'choice' => 'chicken',
);
$this->drupalPost('helloworld/form', $data, 'Submit');
$this->assertText('Your name field is required.', 'Name field is required.');

This code fills in the form on the hellworld/form page, and then clicks the submit button using the DrupalWebTestCase::drupalPost() method. The first argument is the URL at which the form lives, the location to which the HTTP POST request will be sent. The second argument is an associative array of values for the form fields. The keys are the names of the input elements, and the values are the information we would like to enter into those fields.

In this lesson we also make use of the $this->assertFieldByXPath() method, which allows us to select a form element on the page using an XPath selector. In our case, we need to do this because there are actually two input element on the page with their name attribute set to "name", and we need to make sure we're testing the correct one. If you're not familiar with XPath it's worth taking some time to review the syntax since chances are you're going to end up using it at some point when working with SimpleTest.

For more information about these helper methods checkout the API Functions handbook page.

Additional resources

SimpleTest helper methods

XPath documentation