fabian09
fabian09

Reputation: 131

Wait until element is present

I searched through every thread on stackoverflow but couldn't find a suitable solution regarding my issue. In 7/10 cases my scripts are falling because they are not finding one specific element. Therefore i'm searching for an oppurtunity to tell my script "wait so long until this element is present and then click on it".

my code looks like:

require "json"
require "selenium-webdriver"
require "test/unit"

class LogIn < Test::Unit::TestCase

def setup
@driver = Selenium::WebDriver.for :chrome
@base_url = "url"
@accept_next_alert = true
@driver.manage.timeouts.implicit_wait = 30
@verification_errors = []
end
def teardown
@driver.quit
assert_equal [], @verification_errors
end
def test_sms_newsletter
#login
@driver.get "https://secure.shore.com/merchant/sign_in"
@driver.find_element(:id, "merchant_account_email").clear
@driver.find_element(:id, "merchant_account_email").send_keys "key"
@driver.find_element(:id, "merchant_account_password").clear
@driver.find_element(:id, "merchant_account_password").send_keys 
"password"
@driver.find_element(:name, "button").click
@driver.get "https://secure.shore.com"
verify { assert_equal "Shore - Manage your customers", @driver.title }
sleep 5
@driver.find_element(:css, "#asMain > header > a.as-Button.is-
active.as-Button--inverted").click

The element i'm taking about is the last one:

@driver.find_element(:css, "#asMain > header > a.as-Button.is-active.as-Button--inverted").click

Does anyone has an idea?

Upvotes: 0

Views: 3913

Answers (2)

krb224
krb224

Reputation: 345

Here is a snippet to wait for an element is present. You could put a block like this in front of every element before you use it. If the block times out, the test fails.

require 'rubygems'
require 'selenium-webdriver'

browser = Selenium::WebDriver.for :firefox
browser.get "http://localhost/page3"

wait = Selenium::WebDriver::Wait.new(:timeout => 15)

# Add text to a text box
input = wait.until {
    element = browser.find_element(:css, "#asMain > header > a.as-Button.is-active.as-Button--inverted")
    element if element.displayed?
}
input.send_keys("Information")

Upvotes: 2

Shubham Jain
Shubham Jain

Reputation: 17553

The wait should work for you. Try to use FluentWait.

If still the problem exists then use JavascriptExecutor . It will operate directly through JS. It should work if the locator is fine. I am giving an example to click any element using JavascriptExecutor

elementfield = browser.find_element(:css, "#asMain > header > a.as-Button.is-active.as-Button--inverted")
browser.execute_script('arguments[0].click();', elementfield)

Hope it will help you :)

Upvotes: 0

Related Questions