Module Development

Handling Users and Permissions in SimpleTest for Drupal 7

Check your version

This tutorial covers a topic in Drupal 7 which may or may not be the version you're using. We're keeping this tutorial online as a courtesy to users of Drupal 7, but we consider it archived.

Alternate resources

Sprout Video

Typically our application is going to require testing of functionality that is restricted to only users with a certain set of permissions. Like creating a new node for example. In order for the DrupalWebTestCase browser to test these pages we need to first log in to our site. In order to log in we need to have a username and password that we can use to login. In this lesson we'll look at using DrupalWebTestCase::drupalCreateUser() and DrupalWebTestCase::drupalLogin() in order to gain authenticated access to our application and then access and submit a restricted form.

Here's an example of creating a user with the 'administer site configuration` permissions:


$new_user = $this->drupalCreateUser(array('administer site configuration'));

And then logging in as that user:


$new_user = $this->drupalLogin($new_user);

After that the SimpleTest browser will be logged in as that user and all requests that it makes will be authenticated. If you want to return to an anonymous user session you can use the DrupalWebTestCase::drupalLogout() method.

For more information about these helper methods check out the API Functions documentation in the Drupal.org handbook.

SimpleTest helper method documentation

DrupalWebTestCase::drupalLogin()

DrupalWebTestCase::drupalCreateUser()