How can I create variable that can have many string values?

Hi everyone!

I need to create a variable, and manually set its different values, then I need that every time when sending the request it randomly chooses any of these values and put it in the request query.
So, this is the request, It searches photos

GET {{url}}/photos/tags/stars

In the query, “stars” is a keyword, instead of “stars” I want to create a variable that will include many other keywords. For example “sun”, “earth” “flower”, “person” etc.
And everytime when sending the request I need to pick one of these values randomly and use it in the request.

Thanks for the help

just like {{url}} create an array with list of all in items like “sun”, “earth” etc. {{items}} call that item with each request after once by one

var picof = ["Sun", "Earth", "flower", "person"];
pm.environment.set("pictocollect", picof );
var mypics= environment.pictocollect;
var getpics= mypics.pop();

work in test like

tests[getpics] = true;
pm.environment.set("pictocollect", mypics);

just an overview of it, havn’t tested it. a work around like this. hope it helps

you can refer this link as well.

@gpub1’s solution works, but I’m going to offer something slightly different since you said “random every time”

You want to set your pictureKeywords to an array variable. I almost always use collection variables for this, since it relates to the collection, rather than the environment. You can either add this manually to the collection variables, or you can set it in a pre-request script.

const keywords = ['sun', 'earth', 'flower', 'person', 'star'];

To get a random one from the array without modifying it, you can use this pre-request script:

const keywords = ['sun', 'earth', 'flower', 'person', 'star'];
const index = Math.trunc(Math.random() * keywords.length);
const randomKeyword = keywords[index];
pm.collectionVariables.set('keyword', keyword);

In the url for your test, you can now access that variable the same way you had your base url
GET {{url}}/photos/tags/{{keyword}}

1 Like

Tanks for the response,
I did the same as you mentioned, but I’m getting this error: ReferenceError: keyword is not defined

randomKeyword is probably what you need in that set function

pm.collectionVariables.set('keyword', randomKeyword);
1 Like

Thanks @dannydainton, yes.

on line 4 change randomKeyword to just keyword and you’ll be good to go.

3 Likes

Could have probably done this:

const keywords = ['sun', 'earth', 'flower', 'person', 'star'];
pm.collectionVariables.set('keyword', _.shuffle(keywords)[0])

Either way would get you to the same answer though :smiley:

1 Like

I really need to use lodash more. It has everything.

agree on answer but some added value with new addition to test script with _.shuffle :slight_smile:

@allen.helton, @dannydainton @gpub1 Thanks a lot :+1:

1 Like