### Install Gems with Bundler
Source: https://cucumber.io/docs/installation/ruby
After adding gems to the Gemfile, run this command to install them.
```bash
bundle
```
--------------------------------
### Display Cucumber Install Help for Rails
Source: https://cucumber.io/docs/installation/ruby
View the available options for the Cucumber-Rails installation generator.
```bash
rails generate cucumber:install --help
```
--------------------------------
### Cucumber Configuration File Example
Source: https://cucumber.io/docs/cucumber/api
An example of how to define common command-line options within a cucumber.yml file for project-specific configurations.
```yaml
default:
# these are default values
-f pretty
-r features
```
--------------------------------
### Build and Install Cucumber.ml
Source: https://cucumber.io/docs/installation/ocaml
Builds the Cucumber.ml project and installs the cucumber Opam package into your local Opam repository. Ensure gherkin-c is compiled and installed as a shared object beforehand.
```bash
dune build && dune install
```
--------------------------------
### Scenario Outline with Tagged Examples
Source: https://cucumber.io/docs/cucumber/api
In Scenario Outlines, tags can be applied to individual Examples sections to conditionally run them.
```gherkin
Scenario Outline: Steps will run conditionally if tagged
Given user is logged in
When user clicks
Then user will be logged out
@mobile
Examples:
| link |
| logout link on mobile |
@desktop
Examples:
| link |
| logout link on desktop |
```
--------------------------------
### JavaScript Step Definition Example
Source: https://cucumber.io/docs
A step definition written in JavaScript that connects a Gherkin step to an action in the system. This example starts a game with a specific word.
```javascript
When('{maker} starts a game', maker => {
maker.startGameWithWord({ word: 'whale' })
})
```
--------------------------------
### Abstracted Step Example
Source: https://cucumber.io/docs/gherkin/step-organization
This example shows an abstract step that can be parameterized to open different pages. It's useful for reducing duplicate steps that perform a similar action.
```gherkin
Given I go to the {} page
```
--------------------------------
### Scenario Outlines Feature File
Source: https://cucumber.io/docs/guides/parallel-execution
A sample feature file demonstrating scenario outlines with examples.
```gherkin
Feature: Scenario Outlines feature file
Scenario Outline:
Given Step from '' in 'scenario-outlines' feature file
Examples:
| scen_out_row_num |
| Scenario Outline Row 1 |
| Scenario Outline Row 2 |
```
--------------------------------
### Example User Story
Source: https://cucumber.io/docs/terms/user-story
A concrete example of a user story following the standard format, illustrating a mobile banking customer's need.
```gherkin
As an mobile bank customer
I want to see balance on my accounts
So that I can make better informed decisions about my spending
```
--------------------------------
### Conjunction Step Example
Source: https://cucumber.io/docs/guides/anti-patterns
An example of a step that combines multiple actions, which is an anti-pattern. Use built-in conjunctions like 'And' or 'But' instead.
```gherkin
Given I have shades and a brand new Mustang
```
--------------------------------
### Cucumber Configuration File Example
Source: https://cucumber.io/docs/cucumber/configuration
Defines profiles and environment variables in a cucumber.yml file. Use this to set up different testing configurations.
```yaml
##YAML Template
## ie profile executes the browser features with Internet Explorer
default: --profile html_report --profile bvt
html_report: --format progress --format html --out=features_report.html
bvt: --tags @bvt
ie: BROWSER=IE
```
--------------------------------
### Install Cucumber.js with Yarn
Source: https://cucumber.io/docs/tools/javascript
Add Cucumber.js as a development dependency using Yarn. Ensure Node.js and Yarn are installed.
```bash
yarn add --dev @cucumber/cucumber
```
--------------------------------
### Example Parallel Execution Output (TestNG)
Source: https://cucumber.io/docs/guides/parallel-execution
Illustrates the console output when TestNG is used for parallel execution, showing different threads executing scenarios and scenario outline rows.
```text
Thread ID - 15 - Scenario Outline Row 2 from scenario-outlines feature file.
Thread ID - 14 - Scenario Outline Row 1 from scenario-outlines feature file.
Thread ID - 16 - Scenario 1 from scenarios feature file.
Thread ID - 17 - Scenario 2 from scenarios feature file.
```
--------------------------------
### Parallel Execution Output
Source: https://cucumber.io/docs/guides/parallel-execution
Example output demonstrating parallel execution, showing scenarios and scenario outlines executed by different threads.
```text
Thread ID - 13 - Scenario Outline Row 1 from scenario-outlines feature file.
Thread ID - 13 - Scenario Outline Row 2 from scenario-outlines feature file.
Thread ID - 14 - Scenario 1 from scenarios feature file.
Thread ID - 14 - Scenario 2 from scenarios feature file.
```
--------------------------------
### Install Cucumber R from GitHub
Source: https://cucumber.io/docs/installation/r
Use this command to install the cucumber package directly from its GitHub repository using the remotes package.
```r
remotes::install_github("jakubsob/cucumber")
```
--------------------------------
### Procedural Reference Example
Source: https://cucumber.io/docs/bdd/better-gherkin
Avoid this style, which details the implementation steps ('how'). While descriptive, it makes scenarios longer and harder to maintain when the underlying implementation changes.
```gherkin
Given I visit "/login"
When I enter "Bob" in the "user name" field
And I enter "tester" in the "password" field
And I press the "login" button
Then I should see the "welcome" page
```
--------------------------------
### Run Maven Tests
Source: https://cucumber.io/docs/guides/10-minute-tutorial
Execute the Maven test command to verify the Cucumber installation and project setup. This command will run any discovered tests.
```bash
mvn test
```
--------------------------------
### Install Cucumber via Rubygems
Source: https://cucumber.io/docs/installation/ruby
Install the Cucumber gem directly from the command line using Rubygems.
```bash
gem install cucumber
```
--------------------------------
### Feature File with Scenario Outline and Examples
Source: https://cucumber.io/docs/guides/10-minute-tutorial
Defines a feature with a scenario outline that uses variables and examples to test different days of the week.
```gherkin
Feature: Is it Friday yet?
Everybody wants to know when it's Friday
Scenario Outline: Today is or is not Friday
Given today is ""
When I ask whether it's Friday yet
Then I should be told ""
Examples:
| day | answer |
| Friday | TGIF |
| Sunday | Nope |
| anything else! | Nope |
```
--------------------------------
### Ruby Selenium WebDriver Setup and Teardown
Source: https://cucumber.io/docs/guides/browser-automation
Initializes the WebDriver and quits the browser session after all tests are completed. Requires the selenium-webdriver gem.
```ruby
require 'rubygems'
require 'selenium-webdriver'
AfterAll(async function(){
await driver.quit()
});
```
--------------------------------
### Example Gherkin Feature with Detailed Scenarios
Source: https://cucumber.io/docs/terms/user-story
Provides a practical example of Gherkin scenarios for a mobile banking app, covering login and balance display.
```gherkin
Feature: Some important feature
Scenario: Do not show balance if not logged in
Given I am not logged on to the mobile banking app
When I open the mobile banking app
Then I can see a login page
And I do not see account balance
Scenario: Show balance on the accounts page after logging in
Given I have just logged on to the mobile banking app
When I load the accounts page
Then I can see account balance for each of my accounts
```
--------------------------------
### Gherkin Scenario Example
Source: https://cucumber.io/docs
An example of a scenario written in Gherkin syntax, outlining steps for a word guessing game.
```gherkin
Scenario: Breaker guesses a word
Given the Maker has chosen a word
When the Breaker makes a guess
Then the Maker is asked to score
```
--------------------------------
### Data Table Example in Java
Source: https://cucumber.io/docs/cucumber/api
Demonstrates how to use a data table to pass a list of strings to a step definition in Java. The DataTable is automatically flattened.
```gherkin
Given the following animals:
| cow |
| horse |
| sheep |
```
```java
@Given("the following animals:")
public void the_following_animals(List animals) {
}
```
--------------------------------
### Functional Requirement Example
Source: https://cucumber.io/docs/bdd/better-gherkin
Use this style to describe the intended behavior of the system, focusing on the 'what'. This makes scenarios shorter and easier to understand.
```gherkin
When "Bob" logs in
```
--------------------------------
### Combining Profile Execution with Other Arguments
Source: https://cucumber.io/docs/cucumber/configuration
Command-line arguments can be combined with profile execution. This example runs the html_report profile while excluding scenarios tagged with @wip.
```bash
cucumber --profile html_report --tags ~@wip
```
--------------------------------
### Tracking Development Process with Tags
Source: https://cucumber.io/docs/cucumber/api
Employ tags to monitor the development stage of features. For example, '@qa_ready' indicates a feature is ready for quality assurance.
```gherkin
@qa_ready
Feature: Index projects
```
--------------------------------
### Go Step Definition
Source: https://cucumber.io/docs/gherkin/step-organization
A Go implementation for an abstract step pattern. This example uses a regular expression to capture the page name and calls a helper function to open the page.
```go
s.Step(`^I go to the \"([^\"]*)\" page$`, goToPage)
func goToPage(webpage string) error {
return webpageFactory.Open(webpage)
}
```
--------------------------------
### Running Cucumber with Specific Tags
Source: https://cucumber.io/docs/cucumber/api
Command-line example to run Cucumber features tagged with '@authentication'. If the default profile is active, this might yield no results if the profile excludes '@wip' scenarios.
```bash
cucumber --tags=@authentication
```
--------------------------------
### Kotlin Before Hook (Lambda Style)
Source: https://cucumber.io/docs/cucumber/api
Use lambda expressions for Before hooks in Kotlin. This provides a concise way to define setup logic.
```kotlin
Before { scenario: Scenario ->
// doSomething
}
```
--------------------------------
### Scala Before Hook (Lambda Style)
Source: https://cucumber.io/docs/cucumber/api
Use lambda expressions for Before hooks in Scala. This provides a concise way to define setup logic.
```scala
Before { scenario: Scenario =>
// doSomething
}
```
--------------------------------
### Example Scenario for Editing Work Experience
Source: https://cucumber.io/docs/guides/anti-patterns
A sample scenario for adding a description to a CV's work experience. This scenario is coupled to specific step definitions.
```gherkin
Scenario: add description
Given I have a CV and I'm on the edit description page
And I fill in "Description" with "Cucumber BDD tool"
When I press "Save"
Then I should see "Cucumber BDD tool" under "Descriptions"
```
--------------------------------
### Ruby Around Hook (Timeout Example)
Source: https://cucumber.io/docs/cucumber/api
Use Around hooks in Ruby to wrap scenario execution. This example demonstrates failing scenarios tagged with @fast if they exceed a 0.5-second timeout.
```ruby
Around('@fast') do |scenario, block|
Timeout.timeout(0.5) do
block.call
end
end
```
--------------------------------
### Example Parallel Execution Output (CLI)
Source: https://cucumber.io/docs/guides/parallel-execution
Demonstrates the console output when Cucumber is executed via the CLI with parallel threads enabled, indicating distinct threads for scenarios and scenario outline rows.
```text
Thread ID - 11 - Scenario Outline Row 1 from scenario-outlines feature file.
Thread ID - 14 - Scenario 2 from scenarios feature file.
Thread ID - 12 - Scenario Outline Row 2 from scenario-outlines feature file.
Thread ID - 13 - Scenario 1 from scenarios feature file.
```
--------------------------------
### Chai Assertion Library Example
Source: https://cucumber.io/docs/cucumber/checking-assertions
Example of using the Chai assertion library for assertions in JavaScript Cucumber steps. Ensure 'this.actual' is set in a previous step.
```javascript
const { expect } = require('chai')
Then('the result should be {word}', function (expected) {
expect(this.actual).to.eql(expected)
})
```
--------------------------------
### Feature-coupled step definitions directory structure (Kotlin)
Source: https://cucumber.io/docs/guides/anti-patterns
Example directory structure for feature-coupled step definitions in Kotlin. This organization leads to code duplication and high maintenance costs.
```text
features/
+--edit_work_experience.feature
+--edit_languages.feature
+--edit_education.feature
+--steps/
+--edit_work_experience_steps.kt
+--edit_languages_steps.kt
+--edit_education_steps.kt
```
--------------------------------
### Data Table Example in Kotlin
Source: https://cucumber.io/docs/cucumber/api
Shows how to use a data table to pass a list of strings to a step definition in Kotlin. Cucumber automatically flattens the DataTable.
```gherkin
Given the following animals:
| cow |
| horse |
| sheep |
```
```kotlin
@Given("the following animals:")
fun the_following_animals(animals: List) {
}
```
--------------------------------
### Step Definition with Injected AppService (Java)
Source: https://cucumber.io/docs/cucumber/state
Example of a Cucumber step definition class using Google Guice for dependency injection. It injects an AppService and uses it in 'When' and 'Then' steps. Ensure the AppService is correctly bound in your Guice module.
```java
package com.example.app;
import static org.junit.Assert.assertTrue;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Then;
import io.cucumber.guice.ScenarioScoped;
import com.example.app.service.AppService;
import java.util.Objects;
import javax.inject.Inject;
@ScenarioScoped
public final class StepDefinition {
private final AppService appService;
@Inject
public StepDefinition( AppService appService ) {
this.appService = Objects.requireNonNull( appService, "appService must not be null" );
}
@When("the application services are started")
public void startServices() {
this.appService.startServices();
}
@Then("all application services should be running")
public void checkThatApplicationServicesAreRunning() {
assertTrue( this.appService.servicesAreRunning() );
}
}
```
--------------------------------
### Kotlin Selenium WebDriver Steps with Cucumber
Source: https://cucumber.io/docs/guides/browser-automation
Implements Cucumber step definitions in Kotlin using Selenium WebDriver. Features setup, search functionality, and title verification with explicit waits.
```kotlin
package com.example
import io.cucumber.java8.Scenario
import io.cucumber.java8.En
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.WebElement
import org.openqa.selenium.support.ui.WebDriverWait
class ExampleSteps: En {
lateinit var driver: WebDriver
init {
Given("I am on the Google search page") {
driver.get("https:\www.google.com")
}
When("I search for {string}") { query: String ->
val element: WebElement = driver.findElement(By.name("q"))
// Enter something to search for
element.sendKeys(query)
// Now submit the form. WebDriver will find the form for us from the element
element.submit()
}
Then("the page title should start with {string}") { titleStartsWith: String ->
// Google's search is rendered dynamically with JavaScript
// Wait for the page to load timeout after ten seconds
WebDriverWait(driver, 10L).until { d ->
d.title.toLowerCase().startsWith(titleStartsWith)
}
}
After { scenario: Scenario ->
driver.quit()
}
}
}
```
--------------------------------
### Maven Profiles for Environment-Specific Scenarios
Source: https://cucumber.io/docs/cucumber/configuration
Configure separate Maven profiles to run scenarios in different environments by setting cucumber.filter.tags. This example shows profiles for 'dev' and 'qa'.
```xml
dev@dev and not @ignoreqa@qa
...
org.apache.maven.pluginsmaven-surefire-plugin3.0.0-M4${cucumber.filter.tags}
```
--------------------------------
### Java Selenium WebDriver Steps with Cucumber
Source: https://cucumber.io/docs/guides/browser-automation
Implements Cucumber step definitions in Java using Selenium WebDriver. Includes setup for Firefox, searching, and title verification with explicit waits.
```java
package com.example;
import io.cucumber.java.After;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
public class ExampleSteps {
private final WebDriver driver = new FirefoxDriver();
@Given("I am on the Google search page")
public void I_visit_google() {
driver.get("https://www.google.com");
}
@When("I search for {string}")
public void search_for(String query) {
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys(query);
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
}
@Then("the page title should start with {string}")
public void checkTitle(String titleStartsWith) {
// Google's search is rendered dynamically with JavaScript
// Wait for the page to load timeout after ten seconds
new WebDriverWait(driver,10L).until(new ExpectedCondition() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith(titleStartsWith);
}
});
}
@After()
public void closeBrowser() {
driver.quit();
}
}
```
--------------------------------
### Feature-coupled step definitions directory structure (Java)
Source: https://cucumber.io/docs/guides/anti-patterns
Example directory structure for feature-coupled step definitions in Java. This organization leads to code duplication and high maintenance costs.
```text
features/
+--edit_work_experience.feature
+--edit_languages.feature
+--edit_education.feature
+--steps/
+--edit_work_experience_steps.java
+--edit_languages_steps.java
+--edit_education_steps.java
```
--------------------------------
### Feature-coupled step definitions directory structure (JavaScript)
Source: https://cucumber.io/docs/guides/anti-patterns
Example directory structure for feature-coupled step definitions in JavaScript. This organization leads to code duplication and high maintenance costs.
```text
features/
+--edit_work_experience.feature
+--edit_languages.feature
+--edit_education.feature
+--steps/
+--edit_work_experience_steps.js
+--edit_languages_steps.js
+--edit_education_steps.js
```
--------------------------------
### Feature-coupled step definitions directory structure (Ruby)
Source: https://cucumber.io/docs/guides/anti-patterns
Example directory structure for feature-coupled step definitions in Ruby. This organization leads to code duplication and high maintenance costs.
```text
features/
+--edit_work_experience.feature
+--edit_languages.feature
+--edit_education.feature
+--steps/
+--edit_work_experience_steps.rb
+--edit_languages_steps.rb
+--edit_education_steps.rb
```
--------------------------------
### JavaScript Selenium WebDriver Steps with Cucumber
Source: https://cucumber.io/docs/guides/browser-automation
Provides Cucumber step definitions in JavaScript using Selenium WebDriver with Chrome. Includes setup, search, and title assertion using Chai.
```javascript
const { Given, When, Then, AfterAll } = require('cucumber');
const { Builder, By, Capabilities, Key } = require('selenium-webdriver');
const { expect } = require('chai');
require("chromedriver");
// driver setup
const capabilities = Capabilities.chrome();
capabilities.set('chromeOptions', { "w3c": false });
const driver = new Builder().withCapabilities(capabilities).build();
Given('I am on the Google search page', async function () {
await driver.get('http://www.google.com');
});
When('I search for {string}', async function (searchTerm) {
const element = await driver.findElement(By.name('q'));
element.sendKeys(searchTerm, Key.RETURN);
element.submit();
});
Then('the page title should start with {string}', {timeout: 60 * 1000}, async function (searchTerm) {
const title = await driver.getTitle();
const isTitleStartWithCheese = title.toLowerCase().lastIndexOf(`${searchTerm}`, 0) === 0;
expect(isTitleStartWithCheese).to.equal(true);
});
```
--------------------------------
### Navigate to Project Directory
Source: https://cucumber.io/docs/guides/10-minute-tutorial
Change into the newly created project directory after generating it with Maven.
```bash
cd hellocucumber
```
--------------------------------
### JUnit 4 Assertion Example
Source: https://cucumber.io/docs/cucumber/checking-assertions
Example of using JUnit 4's assertEquals in a Cucumber 'Then' step.
```java
import static org.junit.Assert.*;
public class Example {
@Then("the result should be {int}")
public void the_result_should_be(int expectedResult) {
assertEquals(expectedResult, result);
}
}
```
--------------------------------
### Install Cucumber R from CRAN
Source: https://cucumber.io/docs/installation/r
Use this command to install the cucumber package from the Comprehensive R Archive Network (CRAN).
```r
install.packages("cucumber")
```
--------------------------------
### Step Argument Example
Source: https://cucumber.io/docs/cucumber/api
An example of a Gherkin step that includes a numeric argument, which Cucumber extracts and passes to the step definition method.
```gherkin
Given I have 93 cucumbers in my belly
```
--------------------------------
### Declarative BDD Feature Example
Source: https://cucumber.io/docs/bdd/better-gherkin
An example of a BDD feature written in a declarative style, focusing on the intent and abstracting implementation details.
```gherkin
Feature: Subscribers see different articles based on their subscription level
Scenario: Free subscribers see only the free articles
Given Free Frieda has a free subscription
When Free Frieda logs in with her valid credentials
Then she sees a Free article
Scenario: Subscriber with a paid subscription can access both free and paid articles
Given Paid Patty has a basic-level paid subscription
When Paid Patty logs in with her valid credentials
Then she sees a Free article and a Paid article
```
--------------------------------
### Initialize Features Directory
Source: https://cucumber.io/docs/installation/ruby
Generate the initial 'features/' directory structure for your Cucumber project.
```bash
cucumber --init
```
--------------------------------
### RSpec Assertion Example
Source: https://cucumber.io/docs/cucumber/checking-assertions
Example of using RSpec matchers for assertions in Ruby Cucumber steps. Ensure the 'rspec-expectations' gem is added to your Gemfile.
```ruby
Given /^a nice new bike$/ do
expect(bike).to be_shiny
end
```
--------------------------------
### Imperative BDD Feature Example
Source: https://cucumber.io/docs/bdd/better-gherkin
An example of a BDD feature written in an imperative style, detailing specific user actions and expected outcomes.
```gherkin
Feature: Subscribers see different articles based on their subscription level
Scenario: Free subscribers see only the free articles
Given users with a free subscription can access "FreeArticle1" but not "PaidArticle1"
When I type "freeFrieda@example.com" in the email field
And I type "validPassword123" in the password field
And I press the "Submit" button
Then I see "FreeArticle1" on the home page
And I do not see "PaidArticle1" on the home page
Scenario: Subscriber with a paid subscription can access "FreeArticle1" and "PaidArticle1"
Given I am on the login page
When I type "paidPattya@example.com" in the email field
And I type "validPassword123" in the password field
And I press the "Submit" button
Then I see "FreeArticle1" and "PaidArticle1" on the home page
```
--------------------------------
### Splitting Conjunction Steps
Source: https://cucumber.io/docs/guides/anti-patterns
Demonstrates how to split a conjunction step into multiple, more atomic steps using 'And'. This improves reusability and clarity.
```gherkin
Given I have shades
And I have a brand new Mustang
```
--------------------------------
### Gherkin Feature with Scenarios
Source: https://cucumber.io/docs/terms/user-story
Demonstrates a Gherkin feature with two basic scenarios, outlining Given-When-Then steps.
```gherkin
Feature: Some important feature
Scenario: Get something
Given I have something
When I do something
Then I get something else
Scenario: Get something different
Given I have something
And I have also some other thing
When I do something different
Then I get something different
```
--------------------------------
### Generate Cucumber Install for Rails
Source: https://cucumber.io/docs/installation/ruby
Run the Cucumber-Rails generator to set up Cucumber within your Rails application.
```bash
rails generate cucumber:install
```
--------------------------------
### Install Cucumber-JS with Yarn
Source: https://cucumber.io/docs/installation/javascript
Use this command to add Cucumber-JS as a development dependency in your Node.js project when using Yarn.
```bash
yarn add --dev @cucumber/cucumber
```
--------------------------------
### Basic User Story Format
Source: https://cucumber.io/docs/terms/user-story
A standard template for writing user stories, outlining the actor, feature, and benefit.
```gherkin
As an
I want a
So that
```
--------------------------------
### Install Cucumber-JS with npm
Source: https://cucumber.io/docs/installation/javascript
Use this command to add Cucumber-JS as a development dependency in your Node.js project when using npm.
```bash
npm install --save-dev @cucumber/cucumber
```
--------------------------------
### Parallel Execution with Classes and Methods
Source: https://cucumber.io/docs/guides/parallel-execution
Maven Surefire/Failsafe plugin configuration to set parallel execution to 'classesAndMethods'.
```xml
classesAndMethods
useUnlimitedThreads>true
```
--------------------------------
### Advanced Tag Expression Example
Source: https://cucumber.io/docs/cucumber/api
Use parentheses for clarity or to change operator precedence in complex tag expressions.
```gherkin
(@smoke or @ui) and (not @slow)
```
--------------------------------
### Kotlin Step Definition
Source: https://cucumber.io/docs/gherkin/step-organization
A Kotlin implementation for the abstract step 'I go to the {string} page'. Similar to the Java version, it utilizes a factory to open the webpage.
```kotlin
@Given("I go to the {string} page")
fun `I want to open page`(webpage: String) {
webpageFactory.openPage(webpage)
}
```
--------------------------------
### Guard Production Machines from Cucumber
Source: https://cucumber.io/docs/tools/ruby
Provides a safe Rake task for Cucumber that includes error handling for environments where Cucumber might not be installed.
```ruby
require 'rubygems'
begin
require 'cucumber'
require 'cucumber/rake/task'
Cucumber::Rake::Task.new(:features) do |t|
t.cucumber_opts = "--format pretty"
end
task features: 'db:test:prepare'
rescue LoadError
desc 'Cucumber rake task not available'
task :features do
abort 'Cucumber rake task is not available. Be sure to install cucumber as a gem or plugin'
end
end
```
--------------------------------
### Run Cucumber.js from Node Modules
Source: https://cucumber.io/docs/cucumber/api
Command to execute Cucumber.js features from a Node.js project. This assumes Cucumber.js has been installed via npm or yarn.
```bash
./node_modules/.bin/cucumber.js
```
--------------------------------
### Scenarios Feature File
Source: https://cucumber.io/docs/guides/parallel-execution
A sample feature file containing two distinct scenarios.
```gherkin
Feature: Scenarios feature file
Scenario: Scenario Number One
Given Step from 'Scenario 1' in 'scenarios' feature file
Scenario: Scenario Number Two
Given Step from 'Scenario 2' in 'scenarios' feature file
```
--------------------------------
### Java BeforeStep Hook (Lambda)
Source: https://cucumber.io/docs/cucumber/api
Use this lambda style in Java to execute code before each step.
```java
BeforeStep((Scenario scenario) -> {
})
```
--------------------------------
### Gradle Dependencies for Recent Versions (>= 5.0)
Source: https://cucumber.io/docs/installation/java
For Gradle versions 5.0 and newer, use these testImplementation dependencies in your build.gradle or build.gradle.kts file. Ensure mavenCentral() is in your repositories.
```gradle
dependencies {
testImplementation("io.cucumber:cucumber-java:7.34.3")
testImplementation("io.cucumber:cucumber-junit:7.34.3")
}
repositories {
mavenCentral()
}
```
--------------------------------
### Create Cucumber Project with Maven
Source: https://cucumber.io/docs/guides/10-minute-tutorial
Use the cucumber-archetype Maven plugin to generate a new Cucumber project. Ensure you have Maven version 3.3.1 or higher installed.
```bash
mvn archetype:generate \
"-DarchetypeGroupId=io.cucumber" \
"-DarchetypeArtifactId=cucumber-archetype" \
"-DarchetypeVersion=7.34.3" \
"-DgroupId=hellocucumber" \
"-DartifactId=hellocucumber" \
"-Dpackage=hellocucumber" \
"-Dversion=1.0.0-SNAPSHOT" \
"-DinteractiveMode=false"
```
--------------------------------
### Java Step Definition
Source: https://cucumber.io/docs/gherkin/step-organization
A Java implementation for the abstract step 'I go to the {string} page'. This definition uses a factory to open the specified webpage.
```java
@Given("I go to the {string} page")
public void i_want_to_open_page(String webpage) {
webpageFactory.openPage(webpage);
}
```
--------------------------------
### Data Table Example in Scala
Source: https://cucumber.io/docs/cucumber/api
Illustrates passing a list of strings to a step definition in Scala using a data table. Cucumber flattens the DataTable for this purpose.
```gherkin
Given the following animals:
| cow |
| horse |
| sheep |
```
```scala
Given("the following animals:") { animals: java.util.List[String] =>
}
```
--------------------------------
### Run Timeline Formatter from CLI
Source: https://cucumber.io/docs/guides/parallel-execution
Execute the timeline formatter from the command line. This command requires the classpath, the report folder, the thread count for parallel execution, the package for step definitions, and the path to feature files.
```bash
java -cp io.cucumber.core.cli.Main -p timeline: --threads -g
```
--------------------------------
### Stubbing with RSpec in Ruby
Source: https://cucumber.io/docs/cucumber/mocking-and-stubbing-with-cucumber
Example of stubbing a method call using RSpec's `with_temporary_scope` and `stub` for a dependency like SmartyStreets. Ensure `cucumber/rspec/doubles` is required.
```ruby
require 'cucumber/rspec/doubles'
RSpec::Mocks.with_temporary_scope do
stub_resp = {"city"=>"San Francisco", "state_abbreviation"=>"CA", "state"=>"California", "mailable_city"=>true}
SmartyStreets.stub(:get_city_state).with("94109").and_return(stub_resp)
click_button "check zip"
end
```
--------------------------------
### Defining Cucumber YAML Profiles
Source: https://cucumber.io/docs/cucumber/configuration
Define named profiles with associated command-line options in cucumber.yml. This example shows profiles for HTML reporting and BVT tag execution.
```yaml
html_report: --format progress --format html --out=features_report.html
bvt: --tags @bvt
```
--------------------------------
### Ruby Step Definition
Source: https://cucumber.io/docs/gherkin/step-organization
A Ruby implementation for the abstract step 'I go to the {string} page'. This step definition uses a helper method to open the specified web page.
```ruby
Given 'I go to the {string} page' do |page|
open_web_page page
end
```
--------------------------------
### Ruby After Hook (Block Style)
Source: https://cucumber.io/docs/cucumber/api
Define After hooks using a block in Ruby. The 'scenario' object can be used to check the scenario's status, for example, to quit after a failure.
```ruby
After do |s|
# Tell Cucumber to quit after this scenario is done - if it failed.
Cucumber.wants_to_quit = true if s.failed?
end
```