0

How to write If Else condition in selenium for alert box, Here i am using Ruby Language. This is for Login page.. While enter wrong Username, password.. displayed alert box and clicked on ok button.. for this i written followed..

s = Roo::Excelx.new("Login.xlsx")
i=0
j=1
s.each do |data|
    username = data[i]
    password = data[j]
@driver.find_element(:id, "txtUserName").clear
@driver.find_element(:id, "txtUserName").send_keys (username)
@driver.find_element(:id, "txtPassword").clear
@driver.find_element(:id, "txtPassword").send_keys (password)
@driver.find_element(:id, "btnLogin").click
if @driver.find_element(:xpath => "//div[9]/div/button").displayed?
    @driver.find_element(:xpath, "//div[9]/div/button").click
else @driver.find_element(:id, "lblWelcomeName").click
  @driver.find_element(:id, "lnkLogout").click
end

end

when the loop is started second time, the script getting stopped displayed error message like this

 21:        s = Roo::Excelx.new("Login.xlsx")
 22:        i=0
 23:        j=1
 24:        s.each do |data|
 25:                username = data[i]
 26:                password = data[j]

can u please help me to overcome this problem..

SrinivasuluT
  • 7
  • 1
  • 5

1 Answers1

0

First, if you're using Selenium on Ruby I highly recommend you use Watir Webdriver instead. It uses Selenium under the hood, just it's much, much simpler and you can produce understandable code with it. It has a pretty straightforward way to deal with alert boxes (see this: JavaScript Dialogs). For most alert boxes, you want to see if they exist and if they do, either click on it something or enter text and click on the alert. This is very easy with Watir-Webdriver:

# Check if alert is shown
browser.alert.exists?

# Get text of alert
browser.alert.text

# Close alert
browser.alert.ok
browser.alert.close
JAVASCRIPT CONFIRMS
# Accept confirm
browser.alert.ok

# Cancel confirm
browser.alert.close


JAVASCRIPT PROMPT
# Enter text to prompt
browser.alert.set "Prompt answer"

# Accept prompt
browser.alert.ok



# Cancel prompt
browser.alert.close
Alternative Method

You can also make conditional if-then-else statements on alerts, see selenium 2.4.0, how to check for presence of an alert but it is very inconvenient.

Community
  • 1
  • 1
daremkd
  • 8,244
  • 6
  • 40
  • 66