Code Snippet #8 – Postman Variable Command

posted in: Software Testing | 0

In Postman you can set environment or global variables. What are these you might ask? Well, if for example you use the same email address throughout all of your tests, but need to change it. If you don’t use a variable, this would mean ploughing through all of your tests and replacing the email address. Using a variable means you only have to change it in one place. Simple. 

What if I want to set a variable on the fly or from response data? This is where the set variable command comes into it’s own.

The syntax is:

postman.setEnvironmentVariable("NameOfVariableGoesHere", pathToDataToSaveGoesHere);

You can put this code either in with your tests (usually if you don’t need the variable beforehand) or, you can put it in the Pre-request Script section, so it runs before the request is made. This is good for generating random data to include in the request.

 

So, you have now created a variable, but how do I access this saved variable to send in the request? 

The name you gave your variable goes between double braces {{}}. That’s it.

 

Okay, how do I access the created variable to add into my tests?

You prefix the saved variable name with environment.

 

Below are some randomising scripts

postman.setEnvironmentVariable('randomName', "RND"+String((new Date()).getTime()).replace(/\compD/gi,'').substring(7));

The above script creates this string:

RND332115

If you want more or less numbers, just adjust the substring(number).

If you want to do one for email, then simply use this these:

postman.setEnvironmentVariable('firstName', "Bob"+String((new Date()).getTime()).replace(/\compD/gi,'').substring(9));
postman.setEnvironmentVariable('lastName', "Minion"+String((new Date()).getTime()).replace(/\compD/gi,'').substring(9));
postman.setEnvironmentVariable('randomEmail', environment.firstName + environment.lastName +"@minionworld.com");

This generates this string:

Bob1974Minion1975@zuto.com

 

Back

Leave a Reply