Automated Testing With Ruby and Selenium Webdriver

1. Get Start

1
gem install selenium-webdriver

2. Basics Usage

1
2
@driver=Selenium::WebDriver.for :firefox
@wait = Selenium::WebDriver::Wait.new(:timeout => 10)
Navigate
1
@driver.navigate.to 'http://xx.xx.xx.xx'
Switch
1
2
3
4
5
@driver.switch_to.default_content

@driver.switch_to.frame('frame_id')

@driver.switch_to.window('window_id')
Find element
1
2
3
4
5
@driver.find_element(id: 'xxx')
@driver.find_element(name: 'xxx')
@driver.find_element(tag_name: 'xxx')
@driver.find_element(xpath: 'xxx')
@driver.find_element(css: 'xxx')
Click
1
2
el = @driver.find_element()
el.click
Double Click
1
2
el = @driver.find_element()
@driver.action.double_click(el).perform

3. Input

Text
1
2
find_displayed_element(name: 'element_name').clear
find_displayed_element(name: 'element_name').send_keys('123')
Select
1
2
3
4
el = find_displayed_element(name: field_name)
el.find_elements(tag_name: 'option').each_with_index do |option, index|
  option.click if option.text == 'target_text'
end

4. Common functions

1
2
3
4
5
def find_displayed_element(option)
  @wait.until { @driver.find_element(option) }
  @wait.until { @driver.find_element(option).displayed? }
  @driver.find_element(option)
end
1
2
3
4
5
6
def switch_to_displayed_frame(frame_id)
  find_displayed_element(id: frame_id)
  @driver.switch_to.frame(frame_id)

  @driver.execute_script("window.showModalDialog = window.open;");
end
1
2
3
4
5
6
7
8
9
def get_window_id_by_title(window_title)
  @wait.until { @driver.window_handles.size > 1 }

  wnd_titl = @driver.window_handles.map do |w|
    @driver.switch_to.window(w)
    [w, @driver.title]
  end
  win_id = wnd_titl.find{|e1,e2| e2 == window_title }.first
end

5. References

  1. http://docs.seleniumhq.org/
  2. https://code.google.com/p/selenium/wiki/RubyBindings