Combining Steps in Behat for Drupal

Lately I have found myself repeating several lines of behat steps over and over again. Here is a sample of the behat code I use to choose a specific checkbox from an entity browser popup:

There are a few steps in here that are custom, but explaining them would be beyond the scope of this post; just assume they do what they describe (switching focus to an iframe, and clicking a checkbox).

The issue I was having is that every time I wanted to do that one action (pick an image from an entity browser) I was repeating all 8 lines of code.

I began looking for ways of making this set of steps repeatable. After some failed attempts at extending MinkContext and MinkAwareContext I came across scenario hooks via this StackOverflow post. I discovered the @BeforeScenario, which is executed before every scenario in each feature (where it’s used). Using this hook to access contexts from other contexts was documented on but required a few tweaks for the Drupal implementation. Here is what I ended up doing (based on the default FeatureContext.php you get when you install behat for the project:

With this code, I’m able to use a single step in my feature files:

There a few more repeatable groups I’ll probably turn into single step definitions.

The only overhead I can see is that we’re adding $this->minkContext to every scenario even though some may not need it.

Tagged with: ,
Posted in Development

Leave a Reply

Your email address will not be published. Required fields are marked *