3

Is it possible to parameterise a feature file in the same way it is a scenario? So each scenario in the feature could refer to some variables which are later defined by a single table for the entire feature file?

All of the answers I've found so far (Feature and scenario outline name in cucumber before hook for example) use Ruby meta-programming, which doesn't inspire much hope for the jvm setup I'm using.

Community
  • 1
  • 1
MHarris
  • 1,801
  • 3
  • 21
  • 34

2 Answers2

3

No its not, and for good reason. Feature files are meant to be simple and readable, they are not for programming. Even using scenario outlines and tables is generally not a good thing, so taking this further and having a feature that cannot be understood without reading some other thing that defines variables is counter productive.

You can however put all your variables and stuff in step definitions and write your feature at a higher level of abstraction. You'll find implementing this much easier, as you can use a programming language (which is good at this stuff).

diabolist
  • 3,990
  • 1
  • 11
  • 15
2

One way of parameterising a feature file is to generate it from a template at compile-time. Then at runtime your cucumber runner executes the generated feature file.

This is fairly easy to do if you are using gradle. Here is an example:

In build.gradle, add groovy code like this:

import groovy.text.GStringTemplateEngine

task generateFeatureFiles {
    doFirst {
        File featuresDir = new File(sourceSets.main.output.resourcesDir, "features")
        File templateFile = new File(featuresDir, "myFeature.template")
        def(String bestDay, String currentDay) = ["Friday", "Sunday"]
        File featureFile = new File(featuresDir, "${bestDay}-${currentDay}.feature")
        Map bindings = [bestDay: bestDay, currentDay: currentDay]
        String featureText = new GStringTemplateEngine().createTemplate(templateFile).make(bindings)
        featureFile.text = featureText
    }
}

processResources.finalizedBy(generateFeatureFiles)

myFeature.template is in the src/main/resources/features directory and might look like this:

Feature: Is it $bestDay yet?
  Everybody wants to know when it's $bestDay

  Scenario: $currentDay isn't $bestDay
    Given today is $currentDay 
    When I ask whether it's $bestDay yet
    Then I should be told "Nope"

Running the build task will create a Friday-Sunday.feature file in build/src/main/resources with the bestDay and currentDay parameters filled in.

The generateFeatureFiles custom task runs immediately after the processResources task. The generated feature file can then be executed by the cucumber runner.

You could generate any number of feature files from the feature template file. The code could read in parameters from a config file in your resources directory for example.

Joman68
  • 2,248
  • 3
  • 34
  • 36