need changes to watir/loader.rb to make webdriver-user-agent work - user-agent

I am using webdriver-user-agent mentioned here – http://watirwebdriver.com/mobile-devices/
This is the code I am using when trying out this gem
Browser: FF/Chrome
Ruby: 1.9.3 / Selenium :2.30.0 / Watir : 4.0.2
http_client = Selenium::WebDriver::Remote::Http::Default.new
http_client.timeout = HTTP_TIMEOUT
profile = Selenium::WebDriver::Firefox::Profile.new
device = ENV["DEVICE"]
orientation = ENV["ORIENTATION"]
driver = UserAgent.driver(:browser => :firefox, :agent =>device, :orientation=>orientation)
devices = UserAgent.resolution_for(device,orientation)
UserAgent.resize_inner_window(driver,devices[0],devices[1])
Watir::Browser.new driver
Now when the last statement is executed, i get the following error
(STEP) Launching FIREFOX (using web driver user agent)……
browser:
#
undefined method `to_sym’ for # (NoMethodError)
/Users/user/.rvm/gems/ruby-1.9.3-p194/gems/watir-4.0.2/lib/watir/loader.rb:42:in `load_driver_for’
/Users/user/.rvm/gems/ruby-1.9.3-p194/gems/watir-4.0.2/lib/watir/loader.rb:8:in `new’
Based on some investigation, problem is happening at highlighted line below as its trying to .to_sym on the selenium webdriver object.
def load_driver_for(browser)
if browser && browser.to_sym != :ie && Watir.driver == :classic
Watir.driver = :webdriver
end
Watir.load_driver
end
But if we add a line like given below, this gem is working as expected.
def load_driver_for(browser)
if “#{ENV["BROWSER"]}”.eql?(“chrome_useragent”)||”#{ENV["BROWSER"]}”.eql?(“firefox_useragent”)
Watir.driver = :webdriver
else
if browser && browser.to_sym != :ie && Watir.driver == :classic
Watir.driver = :webdriver
end
Watir.load_driver
end
end
since this is watir code outside of our framework, this is not the right way to do this, any suggestion on how to avoid this situation ?

The problem is reproducible when you do:
require 'watir'
require 'webdriver-user-agent'
driver = Webdriver::UserAgent.driver(:browser => :chrome, :agent => :iphone, :orientation => :landscape)
browser = Watir::Browser.new driver
browser.goto 'tiffany.com'
browser.url.should == 'http://m.tiffany.com/International.aspx'
You can fix the issue by requiring watir-webdriver directly instead of through the watir metagem. Change the first line to:
require 'watir-webdriver'

Related

Headless mode in cucumber capybara ruby automation

I have seeing a lot of similar question, but non of them have help me to understand.
how to run my .feature file in headless mode using chromedrive, selenium, capybara, ruby and cucumber.
this is my env.rb:
require_relative 'helper.rb'
BROWSER = ENV['BROWSER']
World(Helper)
Capybara.register_driver :selenium do |app|
if BROWSER.eql?('chrome_headless')
Capybara::Selenium::Driver.new(app,
:browser => :chrome,
:desired_capabilities => Selenium::WebDriver::Remote::Capabilities.chrome(
'chromeOptions' => {
'args' => [ "headless", "window-size=1440x768", "disable-gpu"]
}
)
)
elsif BROWSER.eql?('chrome')
Capybara::Selenium::Driver.new(app,browser: :chrome)
end
end
Capybara.configure do |config|
config.default_driver =:selenium
Capybara.page.driver.browser.manage.window.resize_to(1440,768)
end
Capybara.default_max_wait_time = 60
this is my helper.rb:
module Helper
def take picture(file_name, res)
file_path = "reports/screenshot/"
dateTime = DateTime.now.to_s
dateTime.split(':')
date = dataHora[0..12].to_s+dataHora[14..15].to_s+dataHora[17..21].to_s
picture = "#{file_path}#{date}#{nome_arquivo}-#{res}.png"
temp_shot = page.save_screenshot(picture)
shot = Base64.encode64(File.open(temp_shot, "rb").read)
attach(shot, 'image/png')
end
end
this is my step_definition file .rb
just a normal rb file containing capybara elements
adm = LoginAdmin.new
admInic = TelaInicialAdmin.new
varGlobal = YAML.load(File.read('./configuracoesGlobaisTeste.yaml'))
#nomeOferta = varGlobal["nomeOferta"]
#nomeProduto = varGlobal["nomeProduto"]
Dado('que acessei a página da Vivo') do
acesso.load
end
Quando('clicar em Entrar posso digitar minhas credenciais ') do
page.driver.browser.navigate.refresh
sleep 3
inicio.btnEntrar.click
inicio.usuario.set #usuario
inicio.senha.set #senha
inicio.btnAcessarConta.click
end
is there missing something?
this is how i run the automation on terminal using the tag in my feature file:
cucumber -t#criarClienteCompraLojaClone
this command opens a browser using a GUI. i wish not open GUI. I wish to perform a headless test.
i have just try every tutorial in stackoverflow and google.
Please any suggestion will help!
My headless works updating the env.rb file for this:
require_relative 'helper.rb'
BROWSER = ENV['BROWSER']
#HEADLESS
World(Helper)
Capybara.register_driver :headless_chrome do |app|
Capybara::Selenium::Driver.new(app, browser: :chrome,
options: Selenium::WebDriver::Chrome::Options.new(args: %w[headless no-sandbox disable-gpu]))
end
Capybara.configure do |config|
config.default_driver =:headless_chrome
#Capybara.page.driver.browser.manage.window.resize_to(1440,768)
end
Capybara.default_max_wait_time = 60

How to create chrome profile via Ruby Selenium Binding(or WATIR)

I know how to create profile for Firefox
require 'watir'
options = Selenium::WebDriver::Firefox::Options.new
options.profile = "default"
#driver = Selenium::WebDriver.for :firefox, options: options
#b = Watir::Browser.new #driver
But when I do same thing for Chrome it's not creating, Infact I realized that options(please look above) object doesn't even have the method profile= so I try adding profile like as given below(I saw how people are creating in Java Selenium Binding so I have done the same but it's not working here)
options = Selenium::WebDriver::Firefox::Options.new
options.add_argument('user-data-dir=C:\Users\user_name\AppData\Local\Google\Chrome\User Data\Default')
#driver = Selenium::WebDriver.for :chrome, options: options
Can someone help me how to create Chrome Profile via Ruby Selenium binding(or WATIR)?
Using an existing or creating a new profile can be done via Chromedrivers user-data-dir argument. In Watir, you can pass the argument via the :args parameter:
browser = Watir::Browser.new :chrome,
args: ['user-data-dir=C:\Users\user_name\AppData\Local\Google\Chrome\User Data']
Note that if you trying to use the existing default profile, you do not want to include the "Default" directory in the path.
I made a function for creating new browser. You can use it.
def new_browser
if Rails.env.production?
chrome_bin = ENV.fetch('GOOGLE_CHROME_SHIM', nil)
Selenium::WebDriver::Chrome.path = "/app/.apt/usr/bin/google-chrome"
Selenium::WebDriver::Chrome.driver_path = "/app/vendor/bundle/bin/chromedriver"
end
profile = Selenium::WebDriver::Chrome::Profile.new
profile['general.useragent.override'] = 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10'
driver = Selenium::WebDriver.for :chrome, :profile => profile
pid = driver.instance_variable_get(:#service).instance_variable_get(:#process).instance_variable_get(:#pid)
begin
browser = Watir::Browser.new driver
rescue => e
system("kill -9 #{#pid}")
end
return {:browser => browser , :pid => pid}
end
Since you asked in the comments for a more detailed explanation for Capybara, I post it as an answer (although you seem to already have a working solution now - sorry for the delayed answer).
In my rails projects I usually configure the Selenium chrome driver as follows:
gem 'chromedriver-helper'
in the Gemfile (or install it locally). Then in a system-test initializer define
Capybara.register_driver :selenium_chrome_headless_no_sandbox do |app|
browser_options = ::Selenium::WebDriver::Chrome::Options.new
browser_options.args << '--headless'
browser_options.args << '--disable-gpu'
browser_options.args << '--no-sandbox'
Capybara::Selenium::Driver.new(app, browser: :chrome, options: browser_options)
end
and later (configuring RSpec) I set it as the used driver like:
RSpec.configure do |config|
config.before(:each, type: :system, js: true) do
driven_by :selenium_chrome_headless_no_sandbox
end
end
Maybe this helps someone. Cheers
edit: added chromedriver-helper

Selenium Does Click on Firefox but PhantomJS doesn't (Ruby)

i'm really new to Selenium WebDriver. I write a simple code for out of curiousity. I made an spam bot to open a page, shuffle in online users list and click everyone of them in order. Send some message, close the new window and repeat.
I made this work on Selenium Firefox driver. It seems work good. But i want to do it silent, not opening firefox everytime. So i found out i can do that by PhantomJS.
Here is my working code for firefox:
require 'selenium-webdriver'
def setup
#driver = Selenium::WebDriver.for :firefox
#reklam = 'Some testing message.'
end
def run
setup
#driver.get 'http://c2.me/okanb3'
first_window = #driver.window_handle
begin
#driver.switch_to.window(first_window)
#driver.find_element(link_text: "Shuffle").click
sleep 20
elements = #driver.find_elements(:class, 'shufflelink')
elements.each do |x|
x.click
all_windows = #driver.window_handles
new_window = all_windows.select { |this_window| this_window != first_window }
#driver.switch_to.window(new_window)
if #driver.page_source.include? 'The user is not available right now.' or #driver.page_source.include? 'User account is disabled.'
#driver.close
#driver.switch_to.window(first_window)
else
input = #driver.find_element(:id, 'inputbox')
input.send_keys(#reklam)
input.send_keys:return
#driver.close
popup = #driver.switch_to.alert
popup.accept
#driver.switch_to.window(first_window)
end
end
end while TRUE
end
run
But when i switch Webdriver from Firefox to PhantomJS, x.click method doesn't work. I made some tests and program doesnt go further from click method. After a while program ends with (Net::ReadTimeout) error.
Here is my last try to work it proper;
require 'selenium-webdriver'
def setup
#driver = Selenium::WebDriver.for :phantomjs
#reklam = 'http://peyloride.com siteme beklerim.'
end
def teardown
#driver.quit
end
def run
setup
#driver.manage.window.resize_to(1920, 1080)
#driver.get 'http://c2.me/okanb3'
first_window = #driver.window_handle
begin
#driver.switch_to.window(first_window)
#driver.find_element(link_text: "Shuffle").click
puts "Shuffleandı"
sleep 20
elements = #driver.find_elements(:class, 'shufflelink')
elements.each do |x|
puts "click'e geldik"
#driver.save_screenshot "phantomjs.png"
x.click
#driver.save_screenshot "phantomjs2.png"
puts "click yaptı sonunda aq"
all_windows = #driver.window_handles
new_window = all_windows.select { |this_window| this_window != first_window }
#driver.switch_to.window(new_window)
if #driver.page_source.include? 'The user is not available right now.' or #driver.page_source.include? 'User account is disabled.'
#driver.close
#driver.switch_to.window(first_window)
else
input = #driver.find_element(:id, 'inputbox')
input.send_keys(#reklam)
input.send_keys:return
#driver.close
popup = #driver.switch_to.alert
popup.accept
#driver.switch_to.window(first_window)
end
end
end while TRUE
end
run
As you can see i tried to take a screenshot to understand the problem but screenshot seems really fine. Here it is:
EDIT: Versions:
ruby -v
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux]
gem list
...
selenium-webdriver (2.48.1)
...
phantomjs -v
1.9.0

Ruby Capybara and Firefox: Download file without showing dialog

I am trying to get a Capybara session to automatically save downloaded files in Firefox, without displaying the open/save dialog.
This is my test code:
require 'capybara/dsl'
require 'selenium-webdriver'
cb = Capybara
cb.register_driver :my_firefox_driver do |app|
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.dir'] = "~/Downloads"
profile['browser.download.folderList'] = 2
profile['browser.helperApps.alwaysAsk.force'] = false
profile['browser.download.manager.showWhenStarting'] = false
profile['browser.helperApps.neverAsk.saveToDisk'] = "text/csv"
profile['csvjs.disabled'] = true
Capybara::Selenium::Driver.new(app, :browser => :firefox, :profile => profile)
end
cb.current_driver = :my_firefox_driver
# just to check that we are reaching the correct URL
cb.visit "https://www.google.com/finance/historical?q=NYSE:IBM&startdate=Jan+1%2C+1980&enddate=Sep+18%2C+2014&num=30"
sleep(3)
# attempt a CSV download
cb.visit "https://www.google.com/finance/historical?q=NYSE:IBM&startdate=Jan+1%2C+1980&enddate=Sep+18%2C+2014&output=csv"
sleep(15)
Firefox version is 30. I have tried various profile settings as well as several MIME types, to no avail.
Thanks in advance for any suggestions or solutions.

Ruby Page object Gem - Unable to pick a platform for the provided browser (RuntimeError)

I get this error on running my feature file.
Unable to pick a platform for the provided browser (RuntimeError)
Help required, please.
Here is the code;
class GooglePage
include PageObject
def self.visitor
visit("http://www.google.com")
end
end
env.rb
require 'selenium-webdriver'
require 'page-object'
require 'rubygems'
require 'page-object/page_factory'
World (PageObject::PageFactory)
#browser = Selenium::WebDriver.for :firefox
Step-Definitions
require_relative 'GooglePage'
Given(/^I am on the Google home page$/) do
visit(GooglePage)
# visit('http://www.google.com')
on(GooglePage).visitor
end
This won't work:
visit(GooglePage)
because you haven't called page_url in GooglePage (ln 4 below)
class GooglePage
include PageObject
page_url "http://www.google.com"
def self.visitor
visit("http://www.google.com")
end
end
Move the line #browser = Selenium::WebDriver.for :firefox to the Before method in hooks.rb
Before do
#browser = Selenium::WebDriver.for :firefox
end
After do
#browser.close
end
what if you make your rake file pass on tags and BROWSER and URL,e.g.
rake my_task BROWSER=chrome URL=http://google.com.au
and hooks will check if the BROWSER is chrome, then will use the specific Webdriver for chrome. But how to pass the URL in the PageObject?
Currently from hooks I have the ff:
when "chrome" then
caps = Selenium::WebDriver::Remote::Capabilities.chrome
caps.version = "40.0.2214.115 m"
caps.native_events = false
caps.javascript_enabled= true
# This is for increasing the default timeout to 180
client = Selenium::WebDriver::Remote::Http::Default.new
client.timeout = 180
browser = Selenium::WebDriver.for :chrome
browser.manage.window.maximize
end
Before do
browser.cookies.clear
#browser = browser
end
After do
unless ENV["BROWSER"].eql? "ie"
browser.close
sleep 2
end
end
Then on my HomePage pageobject I have the ff:
class HomePage
include PageObject
page_url("#{ENV['URL']}")
#opens the url defined in ENV['URL']
def goto_homepage
visit(HomePage)
end
end
Using Watir, the URL got opened, so trying this out in Selenium and it won't work.

Resources