Writing Cucumber Features
Explore how to write effective Cucumber feature files using Gherkin language for integration testing in Ruby on Rails applications. Learn to structure scenarios, use Given/When/Then steps, define step definitions with regular expressions, and understand scenario execution with Capybara and Cucumber.
Cucumber features
In Cucumber, we write tests as a series of steps using a minimal language called Gherkin. An individual Cucumber test is called a Scenario, and a group of them is called a Feature.
Integration testing with Cucumber
Let’s take the Capybara integration test from the last section and convert it to Cucumber. Cucumber feature files go in the features directory and typically end in .feature. Here is features_add_task.feature:
This file has three parts. The Feature declaration is at the top. The Cucumber file needs to have one, but the description there is strictly for humans. We can put anything here we want. Gherkin is whitespace-sensitive, so anything that goes beyond that top line needs to be indented.
Ordering tasks
The next section is Background, which is optional. It might not be clear from the preceding code, but the Background line is indented subordinate to Feature. In Cucumber, Background is like Minitest’s setup and RSpec’s before, indicating a run to initialize each test. In our case, since we have only one Scenario, a Background is unnecessary. But if we did have multiple “Add a task” scenarios, they’d likely all share that one common Background.
Cucumber step definitions
After Background ...