Watir Error - Unable to run Watir code example - ruby

On running the following script from http://watir.com/guides/form-example/, I get an error:
# Require the gems we want to use
require 'watir'
require 'webdrivers'
require 'faker'
# Initialize the Browser
browser = Watir::Browser.new
# Navigate to Page
browser.goto 'watir.com/examples/simple_form.html'
# Fill out Text Field Names
browser.text_field(id: 'first_name').set 'Luke'
browser.text_field(id: 'last_name').set 'Perry'
# Use Random Email Address via Faker gem
# Read more about Faker gem here: https://github.com/stympy/faker#readme
random_email = Faker::Internet.email
browser.text_field(id: 'email').set random_email
# Select List:
browser.select(id: 'country').select 'Norway'
# Checkboxes:
browser.checkbox(id: 'interests_cars').click
browser.checkbox(id: 'interests_dentistry').click
# Radio Button:
browser.radio(id: 'newsletter_no').click
# Use RadioSet instead of Radio Button:
browser.radio_set(name: 'newsletter').select('Yes')
# Click Button:
browser.button(id: 'submitButton').click
# Evaluate Results:
browser.p(id: 'name').text == 'Hello Luke Perry,' # => true
browser.p(id: 'newsletter').text == "You will be receiving our newsletter at #{random_email}" # => true
browser.p(id: 'activities').text == 'We hope you continue to enjoy cars, dentistry in Norway' # => true
Here is the error:
DevTools listening on ws://127.0.0.1:61657/devtools/browser/97a9134d-96bb-47f6-83e8-56f09555e71e
[8472:12912:0826/150047.561:ERROR:device_event_log_impl.cc(214)] [15:00:47.561] USB: usb_device_handle_win.cc:1048 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[8472:12912:0826/150047.589:ERROR:device_event_log_impl.cc(214)] [15:00:47.589] USB: usb_device_handle_win.cc:1048 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)>
Any ideas for running the script successfully?
Thanks

Ah, based on the clarification everything is working as intended, there's just some extra noise in the console output based on "Chrome attempting to read properties of USB devices that are currently suspended."
You can safely ignore this message.
Look here for more information:
USB: usb_device_handle_win.cc:1020 Failed to read descriptor from node connection error with ChromeDriver v87 / Chrome v87 using Selenium on Windows10

Related

how to show element in browed page in selenium testing?

I tried this to do selenium testing
require 'watir'
b = Watir::Browser.start 'http://www.gmail.com'
t = b.text_field id: 'entry_1000000'
t.exists?
t.set 'your name'
t.value
but not fetching any text in browed page(www.gmail.com).
require 'watir'
b = Watir::Browser.start 'http://www.gmail.com'
t = b.text_field id: 'entry_1000000'
t.exists?
t.set 'your name'
t.value
put exact id of that text field . id or xpath or name etc
First lets check if you have whats needed for that script to run, and start from there if not.
Ruby installed
Watir gem installed
Browser installed (chrome or firefox)
Geckodriver downloaded and in path (if firefox installed)
Chromedriver downloaded and in path (if chrome installed)
After that, save the code below in file, lets name it gmail.rb.
require 'watir'
b = Watir::Browser.new :chrome #or :firefox
b.goto "www.gmail.com"
b.text_field(:id => 'identifierId').set "your_email#gmail.com"
b.span(:text => "Next").click
b.text_field(:name => "password").set "your_password"
b.span(:text => "Next").click
Open command prompt or terminal and run the following command from folder where gmail.rb is located
ruby gmail.rb
Browser should open, navigate to gmail, input email, password and submit it, but from there gmail security kicks in so this is not a good use case for automation, at least not this way.
You can try the code above and see how it works, and if not, post errors here. But if you actually need to automate reading gmail, there is a really nice gem that helps you do that https://github.com/gmailgem/gmail

Unable to upload a file with Selenium - Ruby

I am trying to upload a file using a bot written in Ruby. It failed but I think my synthax to be good. I suppose that the recent upgrade of Firefox unabled me to do the job. Have you got an idea please ?
I used these resources to do my code :
https://saucelabs.com/resources/articles/best-practices-tips-selenium-file-upload
http://elementalselenium.com/tips/1-upload-a-file
I got the last version of selenium here :
https://rubygems.org/gems/selenium-webdriver/versions/2.53.0?locale=fr
I got the last version of geckodriver here :
https://rubygems.org/gems/geckodriver-helper/versions/0.0.3
But it didn't work : WebDriverError#chrome://marionnette/content/error.js:235:5 File not found
I am using wordpress in local mode with local by flywheel.
Firefox Quantum 57.0 64bits
Here is my little code :
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
run do
#driver.get "http://mywebsite.dev/wp-admin/profile.php"
inputlogin = #driver.find_element :id => "user_login"
inputpwd = #driver.find_element :id => "user_pass"
inputlogin.send_keys "mylogin"
inputpwd.send_keys "mypwd"
#driver.find_element(:id, "wp-submit").click
#driver.get "http://mywebsite.dev"
element = #driver.find_element(:id, 'uploadInput1')
element.send_keys "C:\\path\\image.jpg"
# #driver.find_element(id: 'btn-submit').click
puts "Successful on #{#driver.title}"
end
As it didn't work, I was looking for an other way to upload my file so I tried using AutoIT but I failed... Here is an example.
http://www.maisasolutions.com/blog/How-to-upload-images-using-selenium-webdriver-with-ruby
Moreover, this solution is very heavy (downloads, installations, non reproductability etc.) and don't seems to be proper code.
Thank you for your help.
Find a file field on the page and attach a file given its path.
The file field can be found via its name, id or label text.
page.attach_file(locator, '/path/to/file.png')
Here, locator will beCSS id or class of file upload path.

How to write a simple Cucumber script

I'm following the tutorial to run my first Cucumber script:
Feature: guru99 Demopage Login
In order to Login in Demopage we have to enter login details
Scenario:
Register On Guru99 Demopage without email
Given I am on the Guru99 homepage
When enter blank details for register
Then error email shown
I have the project in Idea but when I run it I get errors.
When using chrome:
Failed to open TCP connection to 127.0.0.1:9515 (No connection could be made because the target machine actively refused it.
I have no idea how to resolve it.
When using Firefox, the script successfully opens the browser but fails after that:
require 'watir'
require 'colorize'
Selenium::WebDriver::Firefox::Binary.path='C:\soft\Mozilla Firefox\firefox.exe'
case ENV['BROWSER']
when 'chrome'
browser = Watir::Browser.new :chrome
when 'firefox'
browser = Watir::Browser.new :firefox
end
Given(/^I am on the Guru99 homepage$/)do
#browser = Watir::Browser.new :firefox
#browser.goto "http://demo.guru99.com"
end
When(/^enter blank details for register$/) do
browser.text_filed(:name,"emaiid").set("")
browser.button(:name,"btnLogin").click
end
Then(/^error email shown$/) do
puts "Email is Required!".red
browser.close
end
And returns:
NoMethodError: undefined method `text_filed' for nil:NilClass
on this line:
browser.text_filed(:name,"emaiid").set("")
I found some references that I need to write a class to call a method. I tried it but didn't succeed.
Connection refused, I'm unsure but "Watir+Cucumber Connection refused" looks a fix.
Copy pasta:
AfterConfiguration do |config|
yourCodeStartUp() # Put your SETUP code here including the launch of webdriver
at_exit
yourCodeTearDown() # Put your CLOSING routine here
puts 'stopped'
end
end
The code error is a typo, it should be browser.text_field(...
Regarding the issue you are observing on chrome, it sounds like you need to update chromedriver (and make sure the exe is in PATH). If you are running chrome v56-58, you need ChromeDriver 2.29.
Regarding the NoMethodError: undefined method error, you have a typo when you call the text_field method (i.e. browser.text_filed).
Nope, I was mistaken, I had an older version of chromedriver. Now it's running in chrome as well. Thank you very much. Appreciate your time!
So, the answers are:
1. Update chromedriver.
2. Check your code for typos one more time.
Was really easy but took me a lot of time%

Browserstack testing IE, Selenium not finding elements that are loaded

Ok --
The issue seems to be resolved -- see below for a working solution.
THE PROBLEM =>
Careful with Selenium's Explicit timeout vs Implicit timeout.
I'm using Browserstack to test IE remotely, via Selenium's Ruby Bindings, running tests via RSpec.
The elements I'm querying are google ad divs, I want to be sure we're serving ads across all our platforms. Loading is asynchronous, so I'm ensuring I wait for page load.
When I manually drive selenium from the ruby shell (irb), I am always able to find the elements in IE, versions 9, 10, 11.
Same when I manually navigate to the site in Browserstack's 'Live' in-browser IE emulation.
BUT -- when I run the same commands as I do in the shell programmatically, via RSpec -- my tests fail about 50% of the time.
IE 11 is the hardest hit, failing most tests.
IE 10 tends to fare a little better.
Same tests for Firefox + Chrome are passing.
Dependencies:
ruby '2.3.0'
gem 'selenium-webdriver'
gem 'rspec'
gem 'curb', '~> 0.9.1'
Any ideas?
describe "Testing example.com in production with ie." do
it "loads ads on home page" do
caps = Selenium::WebDriver::Remote::Capabilities.internet_explorer
caps["browser_version"] = "11.0"
caps["os"] = "WINDOWS"
caps["os_version"] = "8"
caps["resolution"] = "1024x768"
caps["browserstack.debug"] = "true"
driver = Selenium::WebDriver.for(:remote,
:url => "http://<my_username>:<my_pw>#hub.browserstack.com/wd/hub",
:desired_capabilities => caps)
driver.navigate.to "http://www.example.com"
wait = Selenium::WebDriver::Wait.new(:timeout => 5) # seconds
verify = []
begin #
wait.until do
verify = driver.find_elements(:css => "div[id^="google_ads"]")
end
ensure
driver.quit
end
expected_ad_count = 5
expect( verify.count ).to eq expected_ad_count
end
end
THE SOLUTION =>
The explicit wait block was failing for IE.
The solution is, after initializing the driver, to configure implicit wait, as follows:
driver = Selenium::WebDriver.for(:remote,
:url => "http://<my_username>:<my_pw>#hub.browserstack.com/wd/hub",
:desired_capabilities => caps)
driver.manage.timeouts.implicit_wait = 5
driver.navigate.to "http://www.example.com"
begin #
verify = driver.find_elements(:css => "div[id^="google_ads"]")
ensure
driver.quit
end
expected_ad_count = 5
expect( verify.count ).to eq expected_ad_count
And -- it works!
As per your test, I believe your script will continue execution even if there are no elements located using the find_elements(:css => "div[id^="google_ads"]") command. This is because explicit wait only waits for a successful execution of the command and a null response for the find elements command is considered successful.
I would suggest you replace explicit wait with implicit wait in your test. This will help you wait until all the elements are loaded in the DOM and then continue with test execution. You can use the following command in your test to add Implicit wait:
driver.manage.timeouts.implicit_wait = 5 # seconds
Alternatively, you can verify whether all the ads have loaded on the webpage either via JavaScript or jQuery command. Once complete, you can continue with test execution.

Watir Webdriver Load Chrome Extension

I'm trying to load a chrome extension with Watir, and I'm having issues.
I found this related question: Ability to launch chrome with extensions loaded with watir-webdriver. However, I am still having the same issue after following that.
require 'rubygems'
require 'watir-webdriver'
require 'ruby-debug'
require 'nokogiri'
browser = Watir::Browser.new :chrome, :switches => %w[--load-extension=~/.config/google-chrome/Default/Extensions/anepbdekljkmmimmhbniglnnanmmkoja/0.1.12_0]
sleep(10)
browser.close
I also tried copying the extension from /Extensions to /Desktop and loading from there to no avail.
The error I get is Could not load extension from ... Manifest File Missing or Unreadable.
The Manifest file does indeed exist and seems to be a correct file in JSON format.
Trying to load different extensions fails as well.
Download the chrome extension crx file,
Store the args or any other option need to pass in the watir_opts hash
watir_opts[:extensions] = ['path of *.crx file']
browser = Watir::Browser.new :chrome, options: watir_opts
This worked for me.
Note: I didn't encode using 'base64' gem
If you pack the extension and then base64 it, you can load it into the Chrome browser right from your ruby code.
Pack your extension into a *.crx file. You can follow this guide, or just google how to pack a chrome extension.
Base64 it then add it to your desired capabilities list. You could use some code similar to this one:
chrome_extensions = []
chrome_extension_path = '\home\user\packed_chrome_extension.crx'
begin
File.open(chrome_extension_path, "rb") do |file|
chrome_extensions << Base64.encode64(file.read.chomp)
end
rescue Exception => e
raise "ERROR: Couldn't File.read or Base64.encode64 a Chrome extension: #{e.message}"
end
# Append the extensions to your capabilities hash
my_capabilities.merge!({'chrome.extensions' => chrome_extensions})
desired_capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(my_capabilities)
browser = Watir::Browser.new(:remote, :url => 'http://localhost:4444/wd/hub' :desired_capabilities => desired_capabilities)
And don't forget to require 'base64' too.
The example is for a remote web-driver instance, but I think it should work when using web-driver locally too. Just adjust the arguments passed to Watir::Browser.new.

Resources