Does Karate supports a feature where you can define a variable in a scenario and reuse it in other scenarios in the same feature file. I tried doing the same but get an error. What's the best way to reuse the variables within the same feature file ?
Scenario: Get the request Id
* url baseUrl
Given path 'eam'
When method get
Then status 200
And def reqId = response.teams[0]resourceRequestId
Scenario: Use the above generated Id
* url baseUrl
* print 'From the previous Scenario: ' + reqId
Error:
Caused by: javax.script.ScriptException: ReferenceError: "reqId" is not defined in <eval> at line number 1
Use a
Background:section. Here is an example.EDIT: the variable if in the
Background:will be re-initialized for every scenario which is standard testing framework "set up" behavior. You can use hooks such ascallonce- if you want the initialization to happen only once.If you are trying to modify a variable in one scenario and expect it to be now having that modified value when the next
Scenariostarts, you have misunderstood the concept of aScenario. Just combine your steps into oneScenario, because think about it: that is the "flow" you are trying to test.Each
Scenarioshould be able to run stand-alone. In the future the execution order ofScenario-s could even be random or run in parallel.Another way to explain this is - if you comment out one
Scenarioother ones should continue to work.Please don't think of the
Scenarioas a way to "document" the important parts of your test. You can always use comments (e.g.# foo bar). Some teams assume that each HTTP "end point" should live in a separateScenario- but this is absolutely not recommended. Look at the Hello World example itself, it deliberately shows 2 calls, aPOSTand aGET!You can easily re-use code using
callso you should not be worrying about whether code-duplication will be an issue.Also - it is fine to have some code duplication, if it makes the flow easier to read. See this answer for details - and also read this article by Google.
EDIT: if you would like to read another answer that answers a similar question: https://stackoverflow.com/a/59433600/143475