Forum Discussion

TestQA1's avatar
TestQA1
Frequent Contributor
2 years ago

Adding a dynamic/Incrementing variable in Gherkin Scenario in Test Log

Hi,

 

Is there a way we can add a variable in Scenario statement that increments automatically with each next scenario..For Example:

Scenario: 1 Test Case 

Scenario: 2 Test Case 

Scenario: 3 Test Case 

Scenario: 4 Test Case 

 

I don't want to manually change the test case number as often I end up making mistakes in the numbering.

I need them in the test log.

 

Thank you.

 

2 Replies

  • Kitt's avatar
    Kitt
    Regular Contributor

    You'd have to use the 'Scenario Outline' keyword instead of 'Scenario' to accomplish what you're asking. Combined with the 'Background' keyword or Before hook that will run some logic before every scenario this could potentially allow you to create dynamically named titles, BUT it seems overly complicated IMO (see here).

     

    I think the simplest solution is to just write to the log directly. Here's and example function:

     

    function logDynamicTestName() {
      var i;
      for (i = 0; i < 4; i++) {
        var Name = i + " Test Case";
        Log.Message(Name);
      }
    }

     

     

    Not sure what your intent is by doing this or how you are running your tests so I am making some assumptions, but if you're only wanting to track dynamic names/titles in the log I would use the logging function above - IE: make the 'Background' step definition write to the log and increase your counter by 1.

     

    Example in BDD:

     

    Background: Write test case name to the log
    
    Scenario: Test Case
      Given/When/Then

     

     and your step definition would look something like:

     

    When("Write test case name to the log", function (){
      # set a default value of 0 or 1 to the project counter variable then...
      var Name = Project.Variables.Counter + " Test Case";
      Log.Message(Name);
      Project.Variables.Counter++; 
    });

     

     

    Additional references below: 

    [Gherkin - Background] 

    [Gherkin - Before] 

    • Kitt's avatar
      Kitt
      Regular Contributor

      just be sure to reset your counter during clean up ğŸ˜‰