Is there a better way to write code for multiple checkboxes?

Is there a better way to handle verifying when multiple checkboxes are selected or do not exist?
Currently, I input keywords in order such as to verify selected checkboxes:

Checkbox Should Be Selected    //*[@id="a-1-input"]
Checkbox Should Be Selected    //*[@id="b-5-input"]
Page Should Not Contain Checkbox    //*[@id="c-5-input"]

I would like to write code that may be on a single line or just shorter. Does anyone have a suggestion or is what I am doing the best practice?

Really depends on what action I guess you’d want to take, you could do something like:

Checkboxes Selected 
    [Arguments]    ${locator}
    ${els}=    get webelements    ${locator}
    ${len}   Get Length      ${els}

    IF  ${len} > 0
        FOR    ${i}    IN    @{els}
            ${isCheck} =    Run Keyword And Return Status    Checkbox Should Be Selected       ${i}
            #Do something on isCheck.....
        END
    ELSE
        #Do something....
    END

Then call it as:

Checkboxes Selected //*[@type='checkbox']

Locator there will find all of type checkbox, then return all webelements, if no elements are found it will return 0, then it goes to get length of list, if greater than 0 it will check if element is selected and return a true or false.

Its very basic and further exception handling could be done…

just extending on this as another alternative you could pass in a list of locators:

@{list}     create list     //[@id="a-1-input"]     //[@id="b-5-input"]     //*[@id="c-5-input"]
Checkboxes is selected      @{list}

Keyword:

Checkboxes is selected
    [Arguments]    @{locators}
    ${els}=       create list
    FOR     ${i}    IN    @{locators}
        TRY
            ${el}   get webelement    ${i}
            Collections.Append to list      ${els}       ${el}
        EXCEPT
            log    ${i} didnt exists on the page...
        END
    END

    ${len}   Get Length      ${els}
    IF  ${len} > 0
        FOR    ${i}    IN    @{els}
            ${isCheck} =    Run Keyword And Return Status    Checkbox Should Be Selected       ${i}
            #Do something on isCheck.....
        END
    ELSE
        #Do something....
    END

There may be better ways of doing this in RF, also these are just examples I threw together and could be built on / improved to your needs, hope they help anyways or at least gives you some ideas for what you would like build.

Oh, I didn’t give the keyword names much thought, will leave that to you.

1 Like