Smelly Cucumbers

Share this article

It was such a cliche of a title, I just had to use it. I’m sure you have heard of the great BDD tool Cucumber, but what you may not know about is how smelly cukes can be.

I have recently been revising and refactoring my cucumber features in absolute disgust. In my defense, I started writing cucumber in earnest 6-7 months ago. I didn’t spend too much time on it. It was quick to get up and running with a couple of Rails applications, but I stopped using it when I found them becoming clumsy and difficult to maintain.

This was, by no means, any fault of Cucumber. I neglected to learn or develop so much of the tool, that it’s no wonder I ran into troubles. In recent months, I have invested some time in Cucumber again and realized what a chump I had been.

Let’s look at one of the offending Cucumber tests, modified slightly. For what it’s worth, I don’t just make todo applications, but they do make a good example. In this case, it’s a good example of a poor cuke.

Feature: Todo item management

Scenario: Adding a todo item
    Given: I have a todo list named "Mondays list"
    When I go to the home page
    And I fill in "username" with "dave"
    And I fill in "password" with "secret"
    And I press "Log In"
    And I go to the todo page
    And I click on link "Mondays list"
    And I fill in "todo" with "Grab some milk"
    And I press "Add todo"
    Then I should see "Todo item added successfully"

It’s pretty awful yeah? It gets worse, when you realize there are update and delete scenarios.

An Aside – How Cucumbers Work

Before delving any deeper, it’s best we establish the gist of how Cucumber works. You have three component parts:  the feature, scenarios and implementation.

The feature is a scenario, or more likely a collection of scenarios written in Gherkin. I can only describe Gherkin as something like markdown. It’s human readable text with a specific structure and a handful of keywords. The more commonly used/known are Given/When/Then.

Behind these features, we have the implementations which are written in Ruby and more commonly called steps. Each line of a scenario equates to a block of Ruby code.  For example, Given: I have a todo list named "Mondays list" could be implemented like so:

Given /^I have a todo list named "([^"]*)"$/ do |list_name|
  List.create(:name => list_name)
end

Put simply, when Cucumber runs, it scoops up the lines in our scenarios and calls the corresponding step block.

A couple of things to remember is that you treat each scenario in isolation. There is nothing carried over to the next scenario, you need to use some of the special “setup”, “teardown” features of cucumber for that.

Dissecting the Cucumber

Reading back the scenario at the start of the article, I get about a third into reading this test and lose the will to live. Does it describe the behavior of the application? Well, to me all it describes is the mechanics of what I want to do. It’s more a badly written integration test than a description of behavior.

Fortunately for me, scenarios like this are pretty common. I don’t feel so bad knowing that some poor developer out there has suffered the same pain I have.

Nothing is chicken soup to the soul like a bit of self critique. What is so wrong about the accused scenario?

It’s Confusing

We can definitely smell a couple of things wrong here. At first glance, it’s confusing. We have to imagine pages springing into view, populating text fields, pressing buttons. The behavior is lost in lots of pointless detail.

Cucumber was developed in order to involve clients and stakeholders in the development process. We could be dealing with people who may not be technically minded or whose experience of the web may only be lolcats. As great as that may be, asking them to imagine filling out a couple of forms online before making sure we are meeting their requirements is a bit much.

That said, I rarely present my Cucumber scenarios to clients, but I present them to other developers every day. My colleagues are all very familiar with web applications, and the Feature should describe the intended behavior. They do not have to inspect my code and work out what I’m doing. In the interest of time, I can just write them a little story. Also, the story proves to be a great reminder down the line when you are working on your own.

It’s Brittle

Secondly, the test is brittle. What if the log in process changes? Or the login URL? Even if the mechanics of adding a todo item has not changed, the test will fail. That cannot be good news.

It’s Lazy

The final smell is the assertion, or “Then”. What is that actually testing? The Rails flash. It’s a lazy assertion that made me shudder.

Fools Rush In

Over time, I have have been bitten by Cucumber and had to get a bit smart before rushing in to refactoring steps.

Sure, the steps in the above scenario were a snap to write. I hardly had to code any steps in Ruby (the deprecated web_steps.rb handled that for me). However, if I have 20 or so scenarios that require a user to log in and the login URL changes, I’m in trouble. Sure, Vim macros can save some of the pain, but this is not even close to ideal.

Looking at Cucumber in the grand scheme of things, if we slightly modify a scenario, we are really modifying the expected behavior of our application.

In our case a login is pretty slight. We only care if we are logged in, after all. What if we needed to log in with certain credentials to gain privileges? I find it really helps to keep your scenario items as generic as possible.

Doing it Right

It’s time to stop beating myself up and do something about the now infamous scenario. First of all, I want to describe the feature properly. Gherkin allows us to just write text after we declare the feature and it wont kick in until it reaches a keyword.

Feature: Todo item management

I want to track items I need to do in a list. That way I will never forget them. I want to add, edit, delete and mark todo items as finished.

Gherkin actually provides a nice syntax to remove decisions about what to write, it takes the format “In order/As a/I want”. I prefer to write a story, but I could have easily have written:

Feature: Todo item management
  In order to remember things
  As a person with too much on his mind
  I want to maintain todos on a list

I hold my hands up here and say I do not know which is better. I feel the story format has advantages, as we have license to be more descriptive. However, I know more than anyone how daunting a blank screen with a blinking cursor can be. I recommend that you use whichever format works for you, as long as you put in some description of the feature.

Now that we know what we are describing, let’s get to the nitty gritty of refactoring the scenario. The first thing has to be getting rid of all those web steps.

Feature: Todo item management

I want to track items I need to do in a list. That way I will never forget them.
I want to add, edit, delete and mark todo items as finished.
Scenario: Adding a todo item
    Given: I have a todo list named "Mondays list"
    And I am logged in as a normal user
    When I add a todo item "Grab some milk"
    Then it should be added to the todo list

Thats much better, but the log in thing still really bothers me. It is a detail I shouldn’t worry about here. I’m talking about adding a todo item, so why am I distracting myself with this log in nonsense. Luckily, we can handle this using the Gherkin keyword “Background:”.

Feature: Todo item management

I want to track items I need to do in a list. That way I will never forget them. I want to add, edit, delete and mark todo items as finished.

Background:
    Given I am logged in as a normal user

Scenario: Adding a todo item
    Given: I have a todo list named "Mondays list"
    When I add a todo item "Grab some milk"
    Then it should be added to the todo list

The background will act as a setup and run before each scenario in the feature. Background is great, but there is another way, which I tend to use when dealing with logins: Cucumber hooks.

@user_logged_in
  Scenario: Adding a todo item
    Given: I have a todo list named "Mondays list"

I can add the implementation of this hook in a support file along with other roles. It’s especially helpful when using a third party authorization library (such as warden) like so:

Before('@user_logged_in') do
  user = User.create(name: "test_user", admin: false)
  login_as user
end

Now for the step definitions. Written in Ruby they are a real breeze.

Given /^I have a todo list named "([^"]*)"$/ do |list_name|
  @todo_list = Factory.create(:list, name: list_name)
end

When /^I add a todo item "([^"]*)"$/ do |item_description|
  visit todo_path(@todo_List)
  fill_in "Description", with: item_description
  click_button "Add Item"
end

Then /^the Item should be added to the client$/ do
  @todo_list.reload
  @todo_list.items.length.should eql 1
end

I have pointed out a few potential traps we could encounter using Cucumber. Sure, none are really Cucumber’s fault but, like any framework in the wrong hands, it can be nothing but pain. Hopefully, some of what I covered here will save you some trauma. I’m very prone to “am I doing it right” syndrome, but sometimes we just have to feel the pain to learn something new.

I am a firm believer in keeping the scenarios high level. I have read about some developers refusing to use  regex style expressions in the step definitions. If that works for them, great. However, I like to use these regex expressions for setup, sometimes for “When” steps, but never for assertions.

As a rule, try to keep the scenarios tight and don’t try to cover too much of the feature in a single scenario. It sounds like common sense, but I have often been distracted by complementary elements of a feature. Finally, don’t be scared to tear down and re-write “work in progress” scenarios. Cucumber also facilitates a great discovery process for your application. Allow the Cucumber tests to drive your development, always extracting as much testing into your unit tests/specs. If you haven’t started, or even have quit Cucumber testing, I urge you to give it a go. The greatest benefit is knowing the system behaves in an expected way.

Dave KennedyDave Kennedy
View Author

Dave is a web application developer residing in sunny Glasgow, Scotland. He works daily with Ruby but has been known to wear PHP and C++ hats. In his spare time he snowboards on plastic slopes, only reads geek books and listens to music that is certainly not suitable for his age.

Cucumber
Share this article
Read Next
Effortless Content Publishing: A Developer’s Guide to Adobe Experience Manager
Effortless Content Publishing: A Developer’s Guide to Adobe Experience Manager
SitePoint Sponsors
From Idea to Prototype in Minutes: Claude Sonnet 3.5
From Idea to Prototype in Minutes: Claude Sonnet 3.5
Zain Zaidi
Essential Plugins for WordPress Developers: Top Picks for 2024
Essential Plugins for WordPress Developers: Top Picks for 2024
SitePoint Sponsors
WebAssembly vs JavaScript: A Comparison
WebAssembly vs JavaScript: A Comparison
Kaan Güner
The Functional Depth of Docker and Docker Compose
The Functional Depth of Docker and Docker Compose
Vultr
How Top HR Agencies Build Trust Through Logo Designs
How Top HR Agencies Build Trust Through Logo Designs
Evan Brown
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
SitePoint Sponsors
10 Artificial Intelligence APIs for Developers
10 Artificial Intelligence APIs for Developers
SitePoint Sponsors
The Ultimate Guide to Navigating SQL Server With SQLCMD
The Ultimate Guide to Navigating SQL Server With SQLCMD
Nisarg Upadhyay
Retrieval-augmented Generation: Revolution or Overpromise?
Retrieval-augmented Generation: Revolution or Overpromise?
Kateryna ReshetiloOlexandr Moklyak
How to Deploy Apache Airflow on Vultr Using Anaconda
How to Deploy Apache Airflow on Vultr Using Anaconda
Vultr
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Dave NearyAaron Williams
How to Create Content in WordPress with AI
How to Create Content in WordPress with AI
Çağdaş Dağ
A Beginner’s Guide to Setting Up a Project in Laravel
A Beginner’s Guide to Setting Up a Project in Laravel
Claudio Ribeiro
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Gitlab
Creating Fluid Typography with the CSS clamp() Function
Creating Fluid Typography with the CSS clamp() Function
Daine Mawer
Comparing Full Stack and Headless CMS Platforms
Comparing Full Stack and Headless CMS Platforms
Vultr
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Getting Started with Content Collections in Astro
Getting Started with Content Collections in Astro
Tamas Piros
What Does the Java Virtual Machine Do All Day?
What Does the Java Virtual Machine Do All Day?
Peter Kessler
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Mayank Singh
Layouts in Astro
Layouts in Astro
Tamas Piros
.NET 8: Blazor Render Modes Explained
.NET 8: Blazor Render Modes Explained
Peter De Tender
Mastering Node CSV
Mastering Node CSV
Dianne Pena
A Beginner’s Guide to SvelteKit
A Beginner’s Guide to SvelteKit
Erik KückelheimSimon Holthausen
Brighten Up Your Astro Site with KwesForms and Rive
Brighten Up Your Astro Site with KwesForms and Rive
Paul Scanlon
Which Programming Language Should I Learn First in 2024?
Which Programming Language Should I Learn First in 2024?
Joel Falconer
Managing PHP Versions with Laravel Herd
Managing PHP Versions with Laravel Herd
Dianne Pena
Accelerating the Cloud: The Final Steps
Accelerating the Cloud: The Final Steps
Dave Neary
An Alphebetized List of MIME Types
An Alphebetized List of MIME Types
Dianne Pena
The Best PHP Frameworks for 2024
The Best PHP Frameworks for 2024
Claudio Ribeiro
11 Best WordPress Themes for Developers & Designers in 2024
11 Best WordPress Themes for Developers & Designers in 2024
SitePoint Sponsors
Top 10 Best WordPress AI Plugins of 2024
Top 10 Best WordPress AI Plugins of 2024
Dianne Pena
20+ Tools for Node.js Development in 2024
20+ Tools for Node.js Development in 2024
Dianne Pena
The Best Figma Plugins to Enhance Your Design Workflow in 2024
The Best Figma Plugins to Enhance Your Design Workflow in 2024
Dianne Pena
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Christopher Collins
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form