'Can we achieve 'Filtering on Examples' based on karate.env

Can we achieve 'Filtering on Examples' that we have on Jbehave

Sample below:

* def request = { item: '#(item)' }
Examples:
|karate.env:     |item                |
|@dev            |778983-110833-110834|
|@qa             |848079-419456-419457|

What we need to achieve is:

  1. Karate DSL to execute the tests in Examples table based on the current value of karate.env
  2. Karate must create a request = { item: '778983-110833-110834' } if i run tests in dev environment & { item: '848079-419456-419457' } if i run tests in qa.

I was unable to achieve this by using karate.env property but achieved it using the tags, please refer to example below:

Feature:

  Background:
    * url 'https://reqres.in/api'
    * configure headers = { 'Content-Type': 'application/json'}

  Scenario Outline:
    * def reqJson = { "name": "name", "job": "<item>"}
    And path 'users'
    And request reqJson
    When method post
    Then status 201
    And match response.job == '<item>'

    @dev
    Examples:
      | item |
      |   111|

   @qa
    Examples:
      | item |
      |   222|

Triggering on commandline for environment=qa : mvn test -Dcucumber.options="--tags @qa" Triggering on commandline for environment=dev : mvn test -Dcucumber.options="--tags @dev"

Please let me know if there is any other way of achieving it since i wanted to use karate.env property.



Solution 1:[1]

I think you are looking for this: https://github.com/intuit/karate#tags-and-examples

A little-known capability of the Cucumber / Gherkin syntax is to be able to tag even specific rows in a bunch of examples ! You have to repeat the Examples section for each tag. The example below combines this with the advanced features described above.

Scenario Outline: examples partitioned by tag
* def vals = karate.tagValues
* match vals.region[0] == '<expected>'

  @region=US
  Examples:
    | expected |
    | US       |

  @region=GB
  Examples:
    | expected |
    | GB       |

EDIT: for those landing here trying to do this, I suggest another approach, you can call a feature like this:

* call read('foo-' + karate.env + '.feature')

Remember, Karate can read from JSON (or CSV) files and you can use that to drive Examples: https://github.com/intuit/karate#dynamic-scenario-outline

And finally, I don't recommend this much - but if you want to achieve the logic to NOT run a test for a particular karate.env value, you can do this via karate.abort():

* if (karate.env == 'prod') karate.abort()

Just add that line just after the Scenario: and the test will be skipped when needed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1