Search code examples
automationautomated-testsrobotframework

How do I iterate through verifying different texts on a page in Robot Framework?


I've got a functioning Robot Framework test that checks for different texts on a page. It's pretty basic. Scans the page for a specific string, then logs a PASS/FAIL if the string is found. Here's my code.

Test Keyword
    ${p1}=  Run Keyword And Return Status   Page Should Contain Element   xpath=//*[contains(text(), "A")]
    Run Keyword If  ${p1}  Log To Console  "(A) Present"  ELSE  Log To Console  "(A) Not Present"

    ${p2}=  Run Keyword And Return Status   Page Should Contain Element   xpath=//*[contains(text(), "B")]
    Run Keyword If  ${p2}  Log To Console  "(B) Present"  ELSE  Log To Console  "(B) Not Present"

    ${p3}=  Run Keyword And Return Status   Page Should Contain Element   xpath=//*[contains(text(), "C")]
    Run Keyword If  ${p3}  Log To Console  "(C) Present"  ELSE  Log To Console  "(C) Not Present"

This runs perfectly fine, but I'm having trouble making this into a list. Or maybe an array? I'm not sure.

Do I make the xpaths variables inside of the list? Would I make the Run Keyword If statements their own keyword and then just pass those? I'm not sure. Please let me know where I'm going wrong here. Thanks!


Solution

  • What you have in the sample is a repetition of the same code with only one variable - and that is always a good candidate for a loop. This way you'll just pass a different value, doing the same checks.

    FOR    ${a}    IN    A    B    C
    
        ${p}=  Run Keyword And Return Status   Page Should Contain Element   xpath=//*[contains(text(), "${a}")]
        IF  ${p}  Log To Console  "(${a}) Present"  ELSE  Log To Console  "(${a}) Not Present"
    
    END
    

    If the values you're checking are more (or dynamic) and it's not convenient to list them as the looped over, you could put them in a list, and iterate over it:

    ${values}=    Create List   A    B    C
    FOR    ${a}    IN    @{values}
    # the same code follows here