November 8, 2021

The Cheezy Internet: Composing tests using Cucumber and Gherkin

This is fourth in a series of blog posts. Care to go back to the beginning?

Following along with Jeff "Cheezy" Morgan's eBook, "Cucumber and Cheese: A Tester's Workshop" (2017), after setting up a development environment, we started creating in Ruby + Watir the basic building blocks for an automated test framework, as we saw in the last Adventures in Automation blog entry. 

Instead of going into great detail testing against the complex test site Jeff uses in Chapter 4: Cucumbers and Puppies of is book, with Sally's Puppy Adoption Agency, we are using the simpler test site, The-Internet https://the-internet.herokuapp.com/login, by Dave Haeffner. 

This blog post will explore scaffolding a site and composing acceptance tests using Cucumber and Gherkin. 

Scaffolding a Site Using TestGen

It's always a challenge for me when creating a new project to figure out where everything should go. What should the folder and file structure be? Luckily, Jeff Morgan created a Ruby gem called "testgen" which solves all of these problems. 
  • Change the directory to the src folder in your home directory: cd ~/src
  • Pick a name for your project, such as "cheezy_internet"
  • Install Jeff Morgan's Ruby gem testgen on your local machine: gem install testgen 
  • Use the Ruby gem testgen to create a new file hierarchy: testgen project cheezy_internet 

The following files will be created:
PS C:\Users\tmaher\src> testgen project cheezy_internet  
    create cheezy_internet  
    create cheezy_internet/cucumber.yml  
    create cheezy_internet/Gemfile  
    create cheezy_internet/Rakefile  
    create cheezy_internet/features  
    create cheezy_internet/features/support  
    create cheezy_internet/features/step_definitions  
    create cheezy_internet/features/support/env.rb  
    create cheezy_internet/features/support/hooks.rb  
    create cheezy_internet/features/support/pages  
  • Go into the new project folder that was created: cd cheezy_internet
  • Install everything with: bundle install

You can then use VS Code to open the new "cheezy_internet" folder. 

Creating New Test Features in Cucumber

From Cucumber.io / Docs / Overview: "Cucumber is a tool that supports Behaviour-Driven Development(BDD). If you’re new to Behaviour-Driven Development read our BDD introduction first.

"Cucumber reads executable specifications written in plain text and validates that the software does what those specifications say. The specifications consists of multiple examples, or scenarios. [...]

"Each scenario is a list of steps for Cucumber to work through. Cucumber verifies that the software conforms with the specification and generates a report indicating ✅ success or ❌ failure for each scenario. In order for Cucumber to understand the scenarios, they must follow some basic syntax rules, called Gherkin.

"[...] Step definitions connect Gherkin steps to programming code. A step definition carries out the action that should be performed by the step. So step definitions hard-wire the specification to the implementation".

Features Craft Step Definitions

"The purpose of the Feature keyword is to provide a high-level description of a software feature, and to group related scenarios.

"The first primary keyword in a Gherkin document must always be Feature, followed by a : and a short text that describes the feature.

"You can add free-form text underneath Feature to add more description.

"These description lines are ignored by Cucumber at runtime, but are available for reporting (they are included by reporting tools like the official HTML formatter)". - Cucumber.io / Gherkin Reference

Let's say we want to write about the Login feature of The-Internet. We can create a new file under the "features" folder called "Login.feature".

Login.feature
Feature: User Logging into Secure Area

    As an authorized user
    I want to be able to log im
    So that I can access the secure area

    Scenario: Valid User
        Given I arrive on the Login screen
        When I log in using valid credentials
        Then I should arrive at the Secure Area


We can run this features, if we are on the main "cheezy_internet" folder from the command line:

  • cucumber features\Login.feature
Since we don't yet have any step_definitions yet, it gives us samples to go by. If you wanted to you could create a new Ruby file under "step_definitions", and copy and paste the Given, When and Then. 

 1 scenario (1 undefined)  
 3 steps (3 undefined)  
 0m1.906s  
 You can implement step definitions for undefined steps with these snippets:  
 Given('I am on the Login screen') do  
  pending # Write code here that turns the phrase above into concrete actions  
 end  
 When('I log in using valid credentials') do  
  pending # Write code here that turns the phrase above into concrete actions  
 end  
 Then('I should arrive at the Secure Area') do  
  pending # Write code here that turns the phrase above into concrete actions  
 end  

Refine The Feature File


Let's say we wanted to explicitly feed in the username and password into the test, so that we could share the test among many different sets of valid credentials, we could rewrite the feature file: 

Feature: Logging into Secure Area

    As an authorized user
    I want to be able to log im
    So that I can access the secure area

    Scenario: Valid User Login
        Given I am on the Login screen
        When I log in using "tomsmith" and "SuperSecretPassword!"
        Then I should arrive at the Secure Area
        And I should see "Welcome to the Secure Area"

Running the test, and copying-and-pasting into a new file called "login_steps.rb" under the "step_definitions" folder, we get: 

login_steps.rb
Given('I am on the Login screen') do
    pending # Write code here
  end
 
  When('I log in using {string} and {string}') do |string, string2|
    pending # Write code here
  end
 
  Then('I should arrive at the Secure Area') do
    pending # Write code here
  end
 
  Then('I should see {string}') do |string|
    pending # Write code here
  end


Parts of a Step Definition File

Cucumber.io / Gherkin Reference: "Given steps are used to describe the initial context of the system - the scene of the scenario. It is typically something that happened in the past.

"When Cucumber executes a Given step, it will configure the system to be in a well-defined state, such as creating and configuring objects or adding data to a test database.

"The purpose of Given steps is to put the system in a known state before the user (or external system) starts interacting with the system (in the When steps). Avoid talking about user interaction in Given’s. If you were creating use cases, Given’s would be your preconditions [...]

"When steps are used to describe an event, or an action. This can be a person interacting with the system, or it can be an event triggered by another system.

"It’s strongly recommended you only have a single When step per Scenario. If you feel compelled to add more, it’s usually a sign that you should split the scenario up into multiple scenarios. [...]

"Then steps are used to describe an expected outcome, or result.

"The step definition of a Then step should use an assertion to compare the actual outcome (what the system actually does) to the expected outcome (what the step says the system is supposed to do).

"An outcome should be on an observable output. That is, something that comes out of the system (report, user interface, message), and not a behaviour deeply buried inside the system (like a record in a database)".

Fill Out The Step Definition


Let's say we enter the browser test code we came up with in the last blog entry, we get:

login_steps.rb
Given('I am on the Login screen') do
    @browser = Watir::Browser.new :chrome
    @browser.goto 'https://the-internet.herokuapp.com/login'
  end
 
When('I log in using {string} and {string}') do |username, password|
  @browser.text_field(id: 'username').set(username)
  @browser.text_field(id: 'password').set(password)
  @browser.button(value: 'Login').click
end
   
Then('I should see {string}') do |text|
    fail "Expected text not found: #{text}" unless @browser.text.include? text
end


Hrm. The "Then" clause could be better.  Let's use the "expect" RSpec matcher:

Then('I should see {string}') do |expected|
    expect(@browser.text).to include expected
end

Going back to the Given and When clause, we can also replace the parentheses and single quotes with regular expressions and Capture groups.

What are Capture Groups in Cucumber?


Jeff Morgan's "Cucumbers and Cheese":

"Cucumber has something called Capture Groups. This is simply anything that is surrounded by
parentheses. Whatever matches the capture group is placed into a variable passed to the block.
Let’s look at an example. In the previous chapter we had the following step:

"When /^I enter "([^"]*)" in the address field$/ do |address|

"The capture group is ([^"]*) and the value found there is placed in the address parameter.

"We forced this to happen by placing the double quotes around the value in the feature file and
cucumber took this as a clue to create the capture group. The truth is that there is really no need for
the double quotes. If you remove them from both the feature file and step definition you will see
that it works exactly the same.

"The last capture group and regular expression ([^"]*) is somewhat complex. Let’s spend a little
time and see what we can do to simplify it. Here are a few simple things to learn to help you write
simple regular expressions for cucumber.

• "The . character will match any character. For example .. matches “at” and “on” but it doesn’t
match “off” since it is three characters.
• "The * character means zero or more of the previous element so ab* matches “ab”, “abb” and
“a”. a.* matches “a”, “ab”, “abb”, “ac”, etc.
• "The + character means one or more of the previous element so ab+ matches “ab”, “abb” but
does not match “a”. a.+ matches “ab”, “abb”, “ac” but does not match just “a”.
• "Character classes are any set of characters contained within []. For example, [0123456789]
matches any number. [0-9] is shorthand for this example. Another common character class
is [A-Za-z] to represent any alpha character.
• "There are shorthand expressions for character classes. Here are a few: \d is equal to [0-9], \w
is equal to [A-Za-z0-9_], \s is equal to [ \t\r\n\v\f]".

"[^"]*"matches something (or nothing) in double quotes

login_steps:
Given /^I am on the Login screen$/ do
    @browser = Watir::Browser.new :chrome
    @browser.goto 'https://the-internet.herokuapp.com/login'
  end
 
When /^I log in using "([^"]*)" and "([^"]*)"$/ do |username, password|
  @browser.text_field(id: 'username').set(username)
  @browser.text_field(id: 'password').set(password)
  @browser.button(value: 'Login').click
end
   
Then /^I should see "([^"]*)"$/ do |expected|
    expect(@browser.text).to include expected
end

Create a Scenario Outline

What if there were many different valid usernames and passwords you could pick and choose from? 

From Cucumber.io / docs / gherkin: "The Scenario Outline keyword can be used to run the same Scenario multiple times, with different combinations of values [...]. Copying and pasting scenarios to use different values quickly becomes tedious and repetitive [...] We can collapse [...] similar scenarios into a Scenario Outline.

"Scenario outlines allow us to more concisely express these scenarios through the use of a template with < >-delimited parameters"

Cucumber allows us to create a Scenario Outline, where data can be fed into the test, executing once per row of test data. 


Feature: Logging into Secure Area

    As an authorized user
    I want to be able to log in
    So that I can access the secure area

    Scenario Outline: Valid User Login
        Given I am on the Login screen
        When I log in using "<username>" and "<password>"
        Then I should see "Welcome to the Secure Area"

    Examples:
        | username | password             |
        | tomsmith | SuperSecretPassword! |  



Now, we have a (mostly) complete feature file, and an improved step definition file. 

With the next blog article, we will explore adding Page Objects into our little project. 


Happy Testing!

-T.J. Maher
Sr. QA Engineer, Software Engineer in Test
Meetup Organizer, Ministry of Testing - Boston

Twitter | YouTubeLinkedIn | Articles

49 comments:

Harshan said...


Nice blog, it is very impressive.

Bdd With Cucumber Online Course
Cucumber Training in Bangalore

Niyaz said...

Great Post!!! Thanks for it....
what does a Social Media Manager do?
How to Become a Social Media Manager?

Marofa said...

This is good post

Unknown said...

* These are the people who presumably would be open to turning to the health-Insurance exchanges to seek either better options for Insurance, or novel Insurance options. What Is Nsw Ctp Insurance

AT&T Software said...

There is many useful points in this blog. AT&T Software LLC comes with an incredible team of website and mobile application developers who can customize the perfect solutions to transform your business.

hire woocommerce developer
woocommerce development company

Anonymous said...

Incrediwear products increase circulation to reduce inflammation & swelling, relieve pain, restore mobility, and accelerate recovery. Unlike compression products, Incrediwear products do not need to compress to work. Instead, our technology incorporates semiconductor elements within our fabric that releases negative ions when stimulated by body heat.Increasing circulation helps bring more oxygen and nutrients to the target area, which optimizes the body’s natural healing process and accelerates post-operative recovery. Visit https://incrediwear.fitness/ for more.

Milcom Institute said...

Study Advanced Diploma of Telecommunication Network Engineering in Australia. Check the details of these courses - Eligibility, Subjects, Syllabus etc. diploma of telecommunications engineering

สล็อตเครดิตฟรี said...

เล่นผ่านเว็บ pg slot สล็อตเครดิตฟรี ไม่ต้องฝาก ทดลองเล่นโดยไม่ต้องฝาก เล่นได้แบบไม่มีขีดจำกัดตลอด 24 ชั่วโมง รวมทั้งเบิกเงินในปริมาณ พีจี รับเครดิตง่าย ๆ ไม่ต้องฝากก็เล่นได้

jili slot said...

Jili Slot เป็นผู้ให้บริการเกมคาสิโนออนไลน์และก็สล็อตออนไลน์ มีเกมสนุกสนานๆให้เลือกเล่นมาก สามารถเข้าไปเล่น jili slot เล่นผ่านเว็บไซต์ของพวกเราได้เลย ที่เว็บไซต์ pgslot

umeshtyagi said...

Sevenmentor is the best IT traning provider in india which provides wide range of IT courses. Here you will get valuable and authentic study material. Seven mentor is one of the fastest-growing network training institutions in the world and has a monopoly in the region.

The Best IT Training Provider in India

Essien said...

Thank you for taking the time to read a particularly exciting read. I am so glad I found and read. Great process for these contents. A million thanks for sharing.- ekounimed cut off mark for microbiology

Essien said...

It’s actually a nice and helpful piece of information. I am happy that you just shared this amazing and educative piece. Thanks for your effort putting on this piece of knowledge for viewers. ondo city polytechnic admission form closing date

johnstepan said...

I really value the quality writing you put into your blog because it contains important information.
abogados en bancarrota cerca de mi

GwayERP software said...

Thanks for sharing this with us. I found it informative and interesting. Looking forward for more updates. erp software chennai

Pema wangmo said...

Thanks for sharing Nice content! Keep sharing it. Don't miss out on the chance to own a piece of F.R.I.E.N.D.S nostalgia at the best price in the country. Buy F.R.I.E.N.D.S Themed Frames in India. SmewIndia offers the best price in the whole country. Go ahead and order a F.R.I.E.N.D.S Themed Frames.

Pema wangmo said...

Thanks for sharing nice conetent with us! Embrace the captivating charm of canvas embroidery at SmewIndia, where creativity finds its canvas and every thread tells a tale. Allow your surroundings to metamorphose, infusing your life with artistry and depth. Each intricate stitch becomes a whisper of inspiration, guiding your voyage into the enchanting world of art.

Tenzin Jamtsho- Digital Marketer said...

Thank you for sharing wonderful content, Absolutely in love with this anime wall hanging from SMEW India! The attention to detail is incredible, and the colors just pop in my room. It's clear that the artist put their heart and soul into creating this piece. As an anime enthusiast, having this on my wall brings a sense of excitement and nostalgia every time I look at it. The quality is top-notch, and it's definitely a conversation starter for anyone who enters my space. If you're a fellow anime lover, I highly recommend checking out SMEW India's collection – you won't be disappointed!

Pema wangmo said...

You have a nice Post, Keep sharing. As we embrace the beauty of decorative shields let us commend and support organizations like SmewIndia for their tireless endeavors in safeguarding India's artistic legacy for generations to come.

Pema wangmo said...

Thanks for sharing with us, keep sharing it! Explore our curated collection and experience the embodiment of heritage and elegance. Choose SMewIndia for your decorative sword and non-fire arm needs, and let us redefine your appreciation for history and design.

Pema wangmo said...

Thanks for sharing nice content with us! SmewIndia invites you to explore our captivating collection of Harry Potter Themed Frames, where fantasy comes to life in the form of exquisite craftsmanship. Let your love for the wizarding world shine through these frames, and let the magic of Harry Potter continue to enchant your life.

Pema wangmo said...

Thanks for sharing content with us! Exploring and acquiring these exquisite decorative night lights in India is a seamless experience with Smew India. The user-friendly website allows you to browse through the collection, explore intricate details, and make informed choices.

Pema wangmo said...

Thanks for sharing nice content with us, keep sharing! Experience the magic of 3D Paper Cut Shadow Boxes with SmewIndia and let your surroundings come alive with the artistry they bring.

Pema wangmo said...

Thank You so much for sharing with us. When seeking the pinnacle of wooden craftsmanship in India, SmewIndia emerges as a beacon of excellence. Join us as we embark on a journey to uncover the allure of wooden handicrafts and discover the captivating creations offered by SmewIndia.

landscape said...

Thank you for sharing such awesome content. Keep on sharing. Introducing Smewindia's exquisite creation, the "Fairy Light Shadow Box Couple in City." Meticulously handcrafted with utmost care, this charming shadow box captures the essence of a couple beneath a streetlight, offering a unique blend of craftsmanship and aesthetics.

landscape said...

Thank you for sharing such awesome content with us. Experience a new level of elegance in displaying your cherished weapons with our innovative 2 Tier Wall Mount Holder. Designed to create a captivating floating effect, this holder is meticulously crafted to accentuate and showcase your presented weapon, ensuring it takes center stage without any distractions.

landscape said...

This is such an amazing post with awesome content. Introducing the captivating creation by SmewIndia: the remarkable Team 7 Naruto Anime Art and Wall Hanging. Immerse yourself in the world of Naruto with this exquisite depiction of the iconic characters, meticulously crafted by skilled artisans.

landscape said...

This is a fantastic post with aesthetic content. I enjoyed reading it. Introducing our exquisite Harry Potter Wall Art: Hermione – Books and Cleverness, a framed Quilling Art piece that pays tribute to the brilliance of Hermione Granger and her iconic quote.

sonam euden said...

Thank you for sharing nice content with us! Our product Buy Rambo Style Knife for trekking makes for distinctive and cherished presents. They are gifts of admiration and respect, carrying the essence of history and the spirit of warriors who defended their lands.

landscape said...

Thanks for sharing such an amazing post with this awesome content. Keep on sharing. Introducing our exquisite Buy Harry Potter Wall Art – Dobby, a masterpiece of Illustration and quilling Artistry. This high-quality frame boasts meticulous craftsmanship, making it a must-have for Harry Potter enthusiasts and an ideal gift option.

Tenzin Jamtsho said...

Thank you for being so open and honest in your writing. It takes courage to share one's personal experiences and thoughts with the world and your authenticity is truly refreshing. You've created a community here that feels like a warm and supportive virtual family. Clarifying Deluxe Hydrafacial In Bangalore

landscape said...

This is an amazing post with such aesthetic content. Discover the perfect blend of artistry and spirituality with our exquisite Quilling Art - The Buddha,\ an exceptional home decor piece that also makes for a meaningful and thoughtful gift.

sonam euden said...

I appreciate your kind words about the knowledge you provide and your openness to suggestions for enhancing personal growth and well-being. One avenue to explore for self-improvement involves considering opportunities to enhance your skincare and rejuvenation experiences through Maya Medi Spa. They offer an extensive array of services encompassing facials, chemical peels, laser hair removal, body contouring, as well as Injectables at MayaMediSpa such as Botox and dermal fillers. Maya Medi Spa places a strong emphasis on prioritizing customer satisfaction as a cornerstone of their business philosophy. It's noteworthy that Maya Medi Spa specializes in micro treatments and introduces a distinctive approach to beauty routines.

landscape said...

This is an amazing post with such aesthetic content. In the ever-evolving landscape of marketing, the age-old debate of Traditional V/s Digital Marketing stands as a critical juncture for businesses seeking to navigate the realm of customer engagement and brand promotion. As we delve deeper into this dynamic comparison, it becomes evident that the best marketing strategy is not an either-or choice, but rather a synergistic fusion of both worlds

landscape said...

This is an amazing post with such aesthetic content. Illuminate your surroundings with the enchanting allure of the "Buy Quilling Art – Quilled Piano." This meticulously crafted masterpiece is designed to captivate the beholder and infuse any space with a harmonious blend of artistry and elegance.

landscape said...

This is an amazing post with such awesome content. Introducing our exquisite "Buy Quilling Art – Flower Om" frame, a testament to fine craftsmanship and intricate detail. This high-quality frame is more than just a decorative piece – it's a work of art that can enhance your home decor, serve as a thoughtful gift, or grace your wall as a symbol of spiritual significance.

sopfiaa said...

Filing for divorce is never easy, but your blog post has made it much more manageable. Your practical advice and step-by-step breakdown have been instrumental in helping me navigate this process. Thank you for sharing your expertise and making a difference!
Cómo Solicitar el Divorcio en Nueva York

Cheni Wangmo said...

Thank you for sharing your insights and expertise. Your content was very helpful and inspiring. we are grateful for it. Bhutanese Real Estate Regulations

yandenteach said...

Your article is appreciated. The insightful content has the potential to inspire youth, fostering motivation and positive engagement. It provides valuable insights for those aspiring to contribute to the tech sector.thank you
Bhutan Coding Talent

Norbutech said...

Thanks for sharing such awesome content with us Graphic designing services in Bhutan.

Norbusecretsforbetterfuture said...

In the every evolving landscape of Digital, Digital Marketing dominate the world whereby leading your business to success. so choose your Digital Marketing Agency considering every aspect. Email marketing services in BhutanVisit drukdigital.com

landscape said...

Owning a Jaguar is a statement of refined taste, but maintaining its peak performance can become a financial challenge, especially when faced with the need for part replacements. The decision to opt for used parts is driven by the desire to balance luxury with practicality. Unlike new OEM parts that can strain your budget, used Jaguar parts offer a cost-effective solution without compromising on quality.

landscape said...

Thanks for sharing such awesome content with us. If you're a proud owner of an Oldsmobile, you understand the allure of this iconic American brand. Known for their exceptional performance, luxurious features, and timeless design, Oldsmobiles hold a special place in the hearts of automotive enthusiasts. However, as with any vehicle, the need for replacement parts may arise over time, whether for routine maintenance or unexpected repairs. While the cost of new OEM (Original Equipment Manufacturer) parts can put a strain on your budget, there's a smart and cost-effective solution – Oldsmobile Parts Online.

landscape said...

Thanks for sharing such awesome content with us. If you take pride in owning an Oldsmobile, you undoubtedly appreciate the charm of this renowned American brand. Oldsmobiles are celebrated for their exceptional performance, luxurious features, and elegant design. However, like any vehicle, Oldsmobile may require replacement parts over time. Whether it’s for routine maintenance or unforeseen repairs, the cost of new OEM (Original Equipment Manufacturer) parts can strain your finances. This is where high-quality Oldsmobile Parts Online come into play

landscape said...

Thanks for sharing such awesome content with us it's worth reading. Daihatsu Parts offer a cost-effective solution for maintaining your esteemed Japanese brand. Daihatsu vehicles, recognized for outstanding performance, luxurious features, and elegant design, may necessitate replacement parts over time. The expense of new OEM parts can strain your finances, making high-quality Daihatsu Used Auto Parts a sensible choice for unplanned repairs or routine maintenance.

embroidery digitizer said...

Dive into the world of efficient software testing with our comprehensive guide on 'The Cheezy Internet: Composing tests using Cucumber and Gherkin.' Explore the power of Cucumber and Gherkin in crafting effective tests that enhance your application's performance. Elevate your testing experience with our USA digitizer expertise, ensuring precision and innovation in every step. Our skilled team seamlessly integrates Cucumber and Gherkin to create robust testing scenarios, aligning with the highest standards of quality. Trust our USA digitizer services to bring a new level of efficiency to your testing processes, making software development a seamless and reliable experience. Unleash the potential of your applications with the perfect fusion of technology and precision.

Tressa Chirico said...

The Cheezy Internet's guide on using Cucumber and Gherkin for test composition is concise and informative. A valuable resource for streamlining software testing processes.

Vehicle Transportation Services

Logo Digitizing said...

This post highlights the incredible ways new technology is transforming our lives. From smart homes to better healthcare and flexible work options, it's exciting to see how these innovations are creating a more efficient and inclusive future. Thanks for sharing such valuable insights!

Embroidery Digitizing UK said...

Awesome post! Cucumber and Gherkin make testing so much easier and more intuitive. Love how you break down the process—it’s super helpful for anyone getting started with automated testing!

alison said...

while composing tests relax and chill with tiger exchange vip watching your favorite cricket updates anytime