Share This Article
Let’s see how to implement Cucumber in Rails. Cucumber is a tool that helps you test your web application. It does this by running automated tests written in a language called Gherkin.
Gherkin is a plain-text language with a few simple rules. It’s designed to be easy to learn and easy to read.
How Cucumber Works
Cucumber tests are written in Gherkin and stored in files with a .feature
extension.
Each .feature
file can contain one or more scenarios (test cases).
A scenario is made up of a series of steps.
Each step starts with a keyword, like Given
, When
, or Then
.
Let’s take a look at an example.
Here’s a simple scenario that tests a login feature:
gherkin
Feature: Login
As a user,
I want to login to the website,
So that I can access my account
Scenario: Successful login
Given I am on the login page
When I fill in the credentials
Then I should be logged in
Scenario: Failed login
Given I am on the login page
When I fill in the credentials
Then I should see an error message
Understanding Scenarios
Each .feature
file can contain multiple scenarios.
Once you have written your test scenarios, you need to tell cucumber what to do when it encounters each step.
You do this by writing step definitions.
A step definition is a ruby method with a pattern that matches a step in a scenario.
Let’s take a look at an example of a step definition that matches the Given
step in our login scenario:
Given("I am on the login page") do
# code to visit login page
end
Notice that the step definition has a pattern that matches the Given
step in our scenario.
The pattern is a regular expression, so you can be as specific or as general as you want.
In this case, we just want to match the text of the step, but we could have matched the entire step, like this:
Given(/I am on the login page$/) do
# code to visit login page
end
Once you have written your step definitions, you need to tell cucumber where to find them.
You do this by creating a file called cucumber.yml
.
Here’s an example cucumber.yml
file that tells cucumber to look for step definitions in a file called steps.rb
:
yaml
default:
-r steps.rb
Running Cucumber Tests
Once you have written your test scenarios and step definitions, you can run your cucumber tests using the cucumber
command.
For example, if your .feature
file is called login.feature
you can run it like this:
cucumber login.feature
You can also run all your .feature
files at once:
cucumber *.feature
Summary
In this article you’ve learned what cucumber is and how it works. You’ve also learned how to write test scenarios and step definitions, and how to run your cucumber tests.