Skip to main content

_ruby

Example

First we'll set up our requisite libraries to drive the browser (e.g., selenium-webdriver) and perform an assertion (e.g., rspec/expections and RSpec::Matchers). After that, we'll create some simple setup, teardown, and run methods.

# filename: key_presses.rb

require 'selenium-webdriver'
require 'rspec/expectations'
include RSpec::Matchers

def setup
@driver = Selenium::WebDriver.for :firefox
end

def teardown
@driver.quit
end

def run
setup
yield
teardown
end

Now we can write up our test.

Let's use an example from the-internet that will display what key has been pressed (link). We'll use the result text that gets displayed to perform our assertion.

run do
@driver.get 'http://the-internet.herokuapp.com/key_presses'
@driver.find_element(id: 'target').send_keys :space
expect(@driver.find_element(id: 'result').text).to eql('You entered: SPACE')
end

After visiting the page we find an element that's visible (e.g., the one that contains the example on the page (id: 'target')) and send the space key to it (e.g., .send_keys :space). Then we grab the resulting text (e.g., @driver.find_element(id: 'result').text)) and assert that it says what we expect (e.g., 'You entered: SPACE').

Alternatively, we can also issue a key press without finding the element first.

run do
@driver.get 'http://the-internet.herokuapp.com/key_presses'
@driver.action.send_keys(:tab).perform
expect(@driver.find_element(id: 'result').text).to eql('You entered: TAB')
end

Expected Behavior

If we save this and run it (e.g. ruby key_presses.rb from the command-line) here is what will happen:

  • Open the browser
  • Visit the page
  • Find the element and send the space key to it
  • Find the result text on the page and check to that it's what we expect
  • Send the tab key to the element that's currently in focus
  • Find the result text on the page and check to that it's what we expect
  • Close the browser

Summary

If you have a specific element that you want to issue key presses to, then finding the element first is the way to go. If you don't have a receiving element, or you need to string together multiple key presses, then the Action Builder is what you should use.

Happy Testing!