Creating and storing a dynamic variable

My question: This might be a weird one but I’ll explain as best I can. I have a test where I need to generate a random string of 2 words and carry this through to the next two tests

I’m trying to use dynamic variables but having the following issue

In the Pre-Request script I am using something like the below

postman.setEnvironmentVariable("generatedCategory", "#{{$randomWord}} {{$randomWord}}");

This sets the environment variable value to #{{$randomWord}} {{$randomWord}} as expected.

The issue is when I use that stored variable in the body of the next test {{generatedCategory}} it generates new random words instead of the same two that were generated previously

Is there a way that after generating those first random words, I can store them to re-use?

Any help will be appreciated

I’ve already tried:

Just a side note - I have previously tried using the {{$randomWord}} dynamic variable in the test body, and pulling the value from the response to use in the next test - issue here is the response format changes, so the values move about in an array.

Eg. On one one test run I could pull and set the values from using:

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("generatedCategory", jsonData.tags[3]);

and in the next run it was returned in a different object in the array of tags (jsonData.tags[2]) so is not consistent

Hope this makes sense, let me know if you need any more info

@katiepolo,

Yes, you already did a good job here :slight_smile: Still it’s not working because you need to use replaceIn() method here, please refer here for more details about dynamic variables.

In your case, under Pre-request script it should as below:

pm.environment.set("generatedCategory", pm.variables.replaceIn('{{$randomWord}} {{$randomWord}}'));

Now you are good to use {{generatedCategory}} variable :blush:

I hope this helps!!

2 Likes

Thank you so much for this @bpricilla ! This has solved my problem :slight_smile: I have been using Postman for a while but love how I’m still learning new things

Thanks again :slight_smile:

1 Like

@katiepolo I couldn’t agree more to what you said. I feel you, same here :slight_smile: I am learning too :hugs:

All the best :rocket: :partying_face:

1 Like