The Issue
We can use the Ruby puts/print statements to print something in the command window to reflect an action or validation in our script. This can include displaying the value of a variable/expression or describing a problem without failing a step definition. What is the difference between Puts and Print? Puts will add a new line after the command has executed, at the end of the output. Print will continue to output on the same line. Let’s take a look at how we can use these in a Watir Webdriver/Selenium script.
The Code
We can utilize puts/print by placing it before our Watir Webdriver command, as seen in the below example.
1 |
puts (stream.lis(:class, /js-stream-content/)[0].h2.text) |
1 |
print(stream.lis(:class, /js-stream-content/)[0].h2.text) |
In this case, the Watir Webdriver command should be producing some type of output that we pull from the html, which we can display on the command line using puts or print. The below example will use puts.
1 2 3 4 5 6 7 8 |
ta101_puts.rb require 'watir-webdriver' @browser = Watir::Browser.new :chrome @browser.goto('www.yahoo.com') puts('Puts: First Headline on the page') stream = @browser.ul(id: 'Stream') puts(stream.lis(:class, /js-stream-content/)[0].h2.text) @browser.close |
This will validate the first headline on Yahoo.com, and display the output of the headline in the command line. Here is what our command line will display
1 2 |
Puts: First headline on the page Whatever the first headline is |
The output is obtained in this case by the .text command in conjunction with the correct element identifier for the headline. We could also use the .value command to pull our text.
The Takeaway
The puts/print Ruby statements can be utilized in conjunction with your Watir Webdriver/Selenium scripts to display desired info in your command line during an automated test run. You can experiment with the .text and .value Watir Webdriver commands to produce different outputs from the page you are testing.