Creating a Reusable Dictionary of Steps in Cucumber

Posted on by Michael Orr

Corey and I have been using Cucumber to write our integration tests on our current project and I thought I'd share a tip with you that has made our lives so much easier. When making steps in Cucumber, try to make them reusable. The idea behind Cucmber's integration tests is that you are creating a language to talk about (and test) your project. By creating a dictionary of reusable steps we cut down the amount of time it takes to write new features, and decrease the size of the testing language which makes it easier to wrap your head around it. Here is a sample step definition that could be used to check for various http response codes

Then in your feature file you can use this step in multiple tests

Once you've built up a good step dictionary for your project you'll absolutely squeal with delight the first time you write a new scenario using existing step definitions without opening the step definition file to make new steps.

As your library grows you'll find yourself repeating the same series of steps in different scenarios. When this happens, you have identified a common task sequence that can be combined into a single "meta step". It is important to keep separate steps for each of these tasks (see the Conjunction Step Anti-Pattern in the cucumber wiki) but its also nice to create a single meta step to help DRY up your code.

As a simple example, lets say you notice that you often check for both a response code of 200 and a "successfully updated" message on the page with these two steps:

You could add this single step to wrap it up:

This is a simple and useful tip that's easy to implement, and you can start using this today, even on a project that's been around for a while. Keep your code simple, and yourself sane.

Reblog this post [with Zemanta]
 
comments powered by Disqus