The Issue
Sending a key press through to your browser with Ruby & Watir-Webdriver is a functionality with value not immediately obvious, but will be very useful at some point in your browser automation. Uses can include sending the delete key to remove text, the right arrow key to move through an image carousel, or confirm a submission with an enter key. Lets look at how we can to incorporate these into our scripts while browser testing.
The Answer
By using the send_keys command, we can simulate different keyboard inputs, allowing us to broaden our spectrum of test automation scripts and test more with browsers. Here are a few examples:
1 2 3 4 5 |
browser.input(:id,"variable 1").send_keys :enter browser.text_field(:id,"variable 1").send_keys :delete browser.element(:text,"variable 1”).send_keys :tab |
The Code
We will use the send_keys command to send an Enter to a submit button on a form. We will use the Watir Webdriver Demo page for our test form: bit.ly/watir-webdriver-demo.
1 2 3 4 5 6 7 |
#sendkeys.rb require 'watir-webdriver' require 'rubygems' browser = Watir::Browser.new :chrome browser.goto 'bit.ly/watir-webdriver-demo' browser.input(:id,"ss-submit").send_keys :enter puts "Correct error message displays= #{browser.div(:text,"This is a required question").exists?}" |
The Result
Let’s save our automated test script (sendkeys.rb) and run it from the command line. Here is a breakdown of the result:
- Browser opens
- Browser navigates to the Watir Webdriver Demo URL
- Sends the Enter keystroke to the submit button
- We receive a (correct) error message for submitting the form, as the other fields are empty
We can see our confirmation message for sending the enter key on the command line after running:
The Takeaway
You can get creative with send keys and incorporate almost any keystroke into your test automation. This Watir-Webdriver command may help you solve a specific browser automation problem, or just be an alternative way to execute an action in your browser testing scripts.