I am able to use watir-webdriver with IE, but I would prefer to use Firefox.
Problem: I need a proxy.
By googling around, I found some code snippets, but I am not able to put all them together.
This is what I produced up to now, please let me know what am I missing:
require 'watir-webdriver'
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.http", "proxy.myplace.com");
profile.setPreference("network.proxy.http_port", 8080);
WebDriver driver = new FirefoxDriver(profile);
browser = Watir::Browser.new :firefox
browser.goto( "http://www.google.com/" )
I get this error message:
I:/watir/webdriver/webdrivertest.rb:3: syntax error, unexpected tCONSTANT, expec
ting keyword_do or '{' or '('
FirefoxProfile profile = new FirefoxProfile();
Also, I don't know how to use the variable called 'driver'
Call the underlying Selenium WebDriver.
I've used this technique to set a path to Firefox 3.6 so I can test with both Firefox 4 and 3.6:
Selenium::WebDriver::Firefox.path = ENV['FIREWATIRPATH']
browser = Watir::Browser.new :firefox
So to do what you're trying to do:
profile = Selenium::WebDriver::Firefox::Profile.new
proxy = Selenium::WebDriver::Proxy.new(:http => "http://proxy.org:8080")
profile.proxy = proxy
# You have to do a little more to use the specific profile
driver = Selenium::WebDriver.for :firefox, :profile => profile
browser = Watir::Browser.new(driver)
Look at: Selenium Ruby Bindings and Webdriver FAQ for more info.
What problem are you having with the Proxy line?
You could try this:
profile = Selenium::WebDriver::Firefox::Profile.new
profile["network.proxy.type"] = 1
profile["network.proxy.http"] = "proxy.myplace.com"
profile["network.proxy.http_port"] = 8080
The idea is to see what your settings are in about:config and duplicating them in code.
profile = Selenium::WebDriver::Firefox::Profile.new
profile.proxy = Selenium::WebDriver::Proxy.new :http => '12.12.12.12:8888', :ssl => '15.15.15.15:443'
browser = Watir::Browser.new :firefox, :profile => profile
The base problem in your original question is right in the error message
webdrivertest.rb:3: syntax error, unexpected tCONSTANT, expecting keyword_do or '{' or '('
The ruby interpreter is seeing something on the third line of your script that looks like a constant, in a place it's expecting something else.
I suspect it's the start of the line where ruby expects a variable name, and you have a classname. Ruby expects variables named starting with an uppercase to be a constant. which is fine for defining a class, but not creating an instance of one, since the instance won't be a constant.
It also looks like you are trying to do a new invocation using a 'new' keyword ala some other language, instead of using a .new method on whatever object you want to make a new one of, the ruby way.
Compare the code in the answer by Mike where he does
profile = Selenium::WebDriver::Firefox::Profile.new
verses what you were trying to do on line 3
FirefoxProfile profile = new FirefoxProfile();
See how different they are? His is the way to do it.
Related
Running an issue running RSpec and Selenium-Webdriver. Im rolling my own framework and am running into an issue after each test gets ran. My spec_helper.rb setup looks like so:
require 'selenium-webdriver'
Dir['./spec/support/**/*.rb'].each { |file| require file }
RSpec.configure do |config|
config.before(:each) do
# Default browser is chrome, otherwise look for ENV variables
case ENV['browser'] ||= 'chrome'
when 'chrome'
#driver = Selenium::WebDriver.for :chrome
when 'firefox'
#driver = Selenium::WebDriver.for :firefox
end
# Clear cookies between each example
#driver.manage.delete_all_cookies
# Set up implicit waits
#driver.manage.timeouts.implicit_wait = 5
# Default base_url is set to website, otherwise look for ENV variables
case ENV['base_url'] ||= 'https:www.website.com' #redacted real website
when 'local'
ENV['base_url'] = 'local_url_here'
when 'development'
ENV['base_url'] = 'https:www.website.com' #redacted real website
when 'production'
ENV['base_url'] = 'prod_url_here'
end
# Close browser window after each test
config.after(:each) do
#driver.close
end
end
end
My actual rspec tests are setup in the format of:
Rspec.describe 'something' do
context 'some context' do
#multiple it 'stuff' do's
end
end
end
Which is pretty typical. However the first test will run fine, after the first test each test runs fine but the browser (Chromedriver in this case) closes after each test and gives the error: Selenium::WebDriver::Error::WebDriverError: no such session.
So I tried:
config.after(:all) do
#driver.quit
end
Instead. This runs the tests all successfully, but I also get n errors at the end of the test (where n = number of total tests) undefined methodquit' for nil:NilClass`. It also opens a new browser instance for each test (Which I don't want to do).
RSpec seems to close the driver down from what I can tell even without #driver.quit. So im really confused what to do here. I don't want a new browser opening every single instance, but I would like the browser to close after each test and open a new one (Or maybe this is a bad idea?, I am deleting cookies, so if it would just switch to a new URL since I am doing a visit for each test would work?)
What's the best way to handle this?
Yes, that happens when you use chrome driver, it automatically closes the browser at the end.
The solution is to, write the following code for driver object
caps = Selenium::WebDriver::Remote::Capabilities.chrome("goog:chromeOptions" => {detach: true})
driver = Selenium::WebDriver.for :chrome, desired_capabilities: caps
This will stop the chrome browser getting closed at the end.
And I suggest you to use WATIR which is the wrapper around Ruby selenium binding.
Using watir, I've written scripts to check multiple links are being directed to the right page as below.
Links= ["Link", "Link1"]
Links.each do |LinkValue|
#browser.link(:text => LinkValue).wait_until_present.click
fail unless #browser.text.include?(LinkValue)
#browser.back
end
What I am trying is:
maintaining Linktext in an array
iterating with each linktext
verify
navigate to the previous page to start verifying with next linktext.
But the script is not working. It is not executing after first value and also not navigating back.
The following scrip working for me
require 'watir'
browser = Watir::Browser.new(:firefox) # :chrome also work
browser.goto 'https://www.google.com/'
browser.link(text: 'Gmail').wait_until_present.click
sleep(10)
browser.back
sleep(10)
You are calling Kernel::Fail, which will raise an exception if the condition isn't satisfied.
In this case, it looks like you are expecting that the destination page will contain the same link text that was clicked on the originating page. If that's not true, then the script will raise an exception and terminate.
Here's a contrived "working" example (which only "works" because the link text exists on both originating and destination pages):
require 'watir'
b = Watir::Browser.new :chrome
b.goto "http://www.iana.org/domains/reserved"
links = ["Overview", "Root Zone Management"]
links.each do |link|
b.link(:text => link).click
fail unless b.text.include? link
b.back
end
b.close
Some observations:
I wouldn't use fail here. You should investigate a testing framework like Minitest or rspec, which have assertion methods for validating application behavior.
In ruby, variables (and methods and symbols) should be in snake_case.
I am trying to save object definitions in a "home page" file and simply call those methods whenever I need to use that button/link/image/etc. But for some reason the selenium commands are bringing up a NoMethodError. When I simply run the cucumber command while on the features folder in the terminal, I get these errors:
When I click on Site Management # features/step_definitions/steps.rb:17
undefined method `find_element' for nil:NilClass (NoMethodError)
./features/lib/pages/home.rb:3:in `siteMgmt'
./features/step_definitions/steps.rb:18:in `/^I click on Site Management$/'
features/test.feature:6:in `When I click on Site Management'
So in other words, it's trying to "click on site management," the code moves to the Home class, the SiteMgmt method (great!) and then fails when trying to run the selenium find_method method. I thought I might have to add a require selenium-webdriver at the top of home.rb, but a) that's NOT the case in steps.rb and, even if I add it, it doesn't work.
Here is the folder structure:
features/
--test.feature
lib/
pages/
--home.rb
step_definitions/
--steps.rb
support/
--env.rb
env.rb
require 'selenium-webdriver'
Dir[File.dirname(__FILE__) + "/../lib/pages/*.rb"].each {|file| require file }
Before do |scenario|
#driver = Selenium::WebDriver.for :chrome
#url = "URL goes here"
end
After do |scenario|
#driver.quit
end
test.feature
Feature: Proof of Concept
Stack overflow help!
Scenario:
Given I am logged into the site
When I click on Site Management
Then the Site Management page should load
steps.rb
Given(/^I am logged into AMP$/) do
#driver.get #amp_url
end
When(/^I click on Site Management$/) do
link = Home.new.siteMgmt
link.click
end
Then(/^the Site Management page should load$/) do
# assert here
end
home.rb
class Home
def siteMgmt
elem = #driver.find_element(:xpath, '//*[#id="body"]/section[2]/ul/li[1]/h3/a')
return elem
end
end
Thanks for all your help!
The #driver instance variable that's created in the Before block isn't available to an instantiated Home object. You could add a parameter to the site_mgmt method and pass the #driver instance variable in. Here's a contrived example:
class Home
def site_mgmt(driver)
elem = driver.find_element(:id, "logo")
end
end
require 'selenium-webdriver'
#driver = Selenium::WebDriver.for :chrome
#driver.navigate.to "http://www.iana.org/domains/reserved"
link = Home.new.site_mgmt(#driver)
link.click
A couple of notes: 1) variables in ruby are snake_case'd (i.e. site_mgmt instead of siteMgmt; and 2) return elem in site_mgmt isn't needed because ruby methods implicitly return.
Well, it turns out all I had to do is turn #driver to $driver. I'm still learning Ruby and didn't realize the difference.
I've written a Ruby script to automate some user operations using IE.
I'm using Selenium Web Driver for IE. Below is my code.
require 'selenium-webdriver'
browser = Selenium::WebDriver.for :ie
first_window = browser.window_handle
browser.switch_to.frame(browser.find_element(:id=> 'outerFrame'))
browser.switch_to.frame(browser.find_element(:id=> 'innerFrame'))
table_rows = browser.find_element(:id=> 'AllItems').find_element(:tag_name=> 'table').find_elements(:tag_name=> 'tr')
count_cell = table_rows.at(table_rows.length-1).find_elements(:tag_name=> 'td').at(1).find_element(:tag_name=> 'a')
count_cell.click
sleep(5)
all_windows = browser.window_handles
new_window = browser.window_handles.last
browser.switch_to.window(new_window)
btn = browser.find_element(:id=> 'btn_export')
btn.click
At one point, after clicking a button, a new page is opened. Now, when I try to switch to the new window, I get the following error.
C:/Ruby21/lib/ruby/2.1.0/net/http.rb:879:in 'initialize': No
connection could be made because the target machine actively refused
it. - connect(2) for "127.0.0.1" port 5555 (Errno::ECONNREFUSED)
from C:/Ruby21/lib/ruby/2.1.0/net/http.rb:879:in 'open'
from C:/Ruby21/lib/ruby/2.1.0/net/http.rb:879:in 'block in connect'
from C:/Ruby21/lib/ruby/2.1.0/timeout.rb:75:in 'timeout'
from C:/Ruby21/lib/ruby/2.1.0/net/http.rb:878:in 'connect'
from C:/Ruby21/lib/ruby/2.1.0/net/http.rb:863:in 'do_start'
from C:/Ruby21/lib/ruby/2.1.0/net/http.rb:852:in 'start'
from C:/Ruby21/lib/ruby/2.1.0/net/http.rb:1375:in 'request'
from C:/Ruby21/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/http/default.rb:107:in 'response_for'
from C:/Ruby21/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/http/default.rb:58:in
'request'
from C:/Ruby21/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/http/common.rb:59:in
'call'
from C:/Ruby21/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/bridge.rb:664:in
'raw_execute'
from C:/Ruby21/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/bridge.rb:642:in
'execute'
from C:/Ruby21/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/bridge.rb:216:in
'switchToWindow'
from C:/Ruby21/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/common/target_locator.rb:81:in
'window'
from script.rb:18:in ''
I tried my bit to resolve the error, by modifying firewall and added rules for port 5555. Even then issue persists. I found some already exsting questions on this, but most of them are related to Java or .Net. How can I resolve this error? Can anyone point me in the right direction?
I am not a ruby expert, but I have seen similar problems happening. I have a Python-ic solution. All you need to do is Ruby-fy the code. https://gist.github.com/ab9-er/08c3ce7d2d5cdfa94bc7
def change_window(browser):
"""
Simple window switcher without the need of playing with ids.
#param browser: Current browser instance
"""
curr = browser.current_window_handle
all_handles = browser.window_handles
for handle in list(set([curr]) - set(all_handles)):
return browser.switch_to_window(handle)
Try switching back to the top level browsing context before switching to a new window.
browser.switch_to.default_content
current_window = browser.window_handle
new_window = browser.window_handles.find { |win| win != current_window }
browser.switch_to.window(new_window)
It should do this implicitly, so if it isn't, it's likely a bug. If this works, please let me know so I can see if we need to file a bug report.
I am trying to use capybara-poltergeist with proxy to emulate a browser.
require 'capybara/poltergeist'
require 'capybara/dsl'
Capybara.register_driver :poltergeist_proxy do |app|
Capybara::Poltergeist::Driver.new(app,:js_errors => false,{ :phantomjs_options => ['--ignore-ssl-errors=yes', '--proxy-type=https','--proxy=112.124.46.186:80'] })
end
Capybara.current_driver = :poltergeist_proxy
Capybara.default_wait_time = 90
Capybara.app_host = 'https://www.bbc.co.uk'
visit('/')
Unfortunately, I am getting the following error -
/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/poltergeist-1.5.0/lib/capyb
ara/poltergeist/web_socket_server.rb:87:in `rescue in send': Timed out waiting for response to {"name":"visit","args":["https://www.bbc.co.uk/"]}. It's possible that this happened because something took a very long time (for example a page load was slow). If so, setting the Poltergeist :timeout option to a higher value will help (see the docs for details). If increasing the timeout does not help, this is probably a bug in Poltergeist - please report it to the issue tracker. (Capybara::Poltergeist::TimeoutError)
I am not sure what mistake I am making. I know the syntax I am using is correct, based on a related query here, as well as mentioned at the github.
I don't think https is a valid proxy type (see https://github.com/ariya/phantomjs/wiki/API-Reference). Also, you can try adding timeout: 180 to your driver options