login

Logging in as an existing user in a Behat test with the Drupal Extension

There are some occasions when I want my Drupal Behat tests to perform some action as a user that already exists on the Drupal site. For example, I have a test install profile with some Default Content (users, nodes, taxonomy terms, etc.), and it already has a large set of default test data set up on the site for the benefit of developers who need to work on theming/site building.

Rather than define a ton of extra Behat steps to re-create all this test content and these test users, I just want Behat to log in as an existing user and perform actions with the pre-existing content.

Note that this might not be a good idea depending on the structure or philosophy of your site's testing. As a general principle, state should be avoided—and that includes things like 'having a set of default stuff already existing before a test runs'. However, in the real world there are situations where it's a ton easier to just use the state that exists ?.

The problem

Out of the box, the Drupal API Driver lets you create a user in a Scenario and then use that created user, like so:

How to redirect a user after login to a specific page

There are some simple Drupal modules that help with login redirection (especially Login Destination), but I often need more advanced conditions applied to redirects, so I like being able to do the redirect inside a custom module. You can also do something similar with Rules, but if the site you're working on doesn't have Rules enabled, all you need to do is:

  1. Implement hook_user_login().
  2. Override $_GET['destination'].

The following example shows how to redirect a user logging in from the 'example' page to the home page (Drupal uses <front> to signify the home page):