Is it possible to generate dynamic variable names in Karate?

Viewed 135

I am making a REST API call which returns a response like this

{"id":"726295ab-d6bc-4f09-8cb7-6f6f54fc9364", "name":"Customer Data"}

I create 5 objects like this and I want to store the ids of all the 5 objects from response in 5 different variables.

I tried using something like

* def catID_<categoryName> = $.id

and provided the name of the object in the Examples section. It works fine most of the times except when the name has spaces in it.

no step-definition method match found for: * def catID_Customer Data = $.id

Is it possible to do something like this?

* def catName = replace all spaces in the name with _

* def #(catName)_id = $.id

or is there a better way to achieve this?

1 Answers

You seem to be doing things Karate is not designed to do, so by default please assume that this is not supported.

Most likely, adding keys to a JSON object is a more elegant approach instead of trying to dynamically hack def. For example:

* def variables = {}
* variables['<someDynamicName>'] = $.id
# then later
* print variables['actual name']

Also note that the '< and >' are not required: https://github.com/karatelabs/karate#scenario-outline-enhancements

Related