Best Selenium code snippet using Selenium.WebDriver.Remote.session_id
settings.rb
Source: settings.rb
...238 # * +string+ - URL address of last running Sauce Labs job239 #240 def sauce_resource_path(name)241 host = "https://#{settings.sl_user}:#{settings.sl_api_key}@saucelabs.com"242 path = "/rest/#{settings.sl_user}/jobs/#{session_id}/results/#{name}"243 "#{host}#{path}"244 end245 ##246 #247 # Sends http request to change current Sauce Labs job status - pass/fail248 #249 # *Parameters:*250 # * +json_data+ - test status as hash (for details see Saucelab documentation)251 #252 def update_sauce_job_status(json_data = {})253 host = "http://#{settings.sl_user}:#{settings.sl_api_key}@saucelabs.com"254 path = "/rest/v1/#{settings.sl_user}/jobs/#{session_id}"255 url = "#{host}#{path}"256 ::RestClient.put url, json_data.to_json, content_type: :json, accept: :json257 end258 ##259 #260 # Returns custom name for Sauce Labs job261 #262 # *Returns:*263 # * +string+ - Return name of current Sauce Labs job264 #265 def suite_name266 res = if ENV['RAKE_TASK']267 res = ENV['RAKE_TASK'].sub(/(?:r?spec|cucumber):?(.*)/, '\1').upcase268 res.empty? ? 'ALL' : res269 else270 'CUSTOM'271 end272 "#{res} #{settings.sl_browser_name.upcase}"273 end274 ##275 #276 # Returns current session id277 #278 def session_id279 Capybara.current_session.driver.browser.instance_variable_get(:@bridge).session_id280 end281 module_function :session_id282 ##283 #284 # Returns custom name for rake task285 #286 # *Returns:*287 # * +string+ - Returns rake task name288 #289 def rake_task_name290 ENV['RAKE_TASK'].to_s.sub(/(?:r?spec|cucumber):?(.*)/, '\1').upcase291 end292 Capybara.run_server = false293 Capybara.app_host = ''294 Capybara.asset_host = app_base_url295 Capybara.default_max_wait_time = settings.timeout_small...
bridge.rb
Source: bridge.rb
...27 bridge = new(opts)28 capabilities = bridge.create_session(desired_capabilities)29 case bridge.dialect30 when :oss # for MJSONWP31 Bridge::MJSONWP.new(capabilities, bridge.session_id, opts)32 when :w3c33 Bridge::W3C.new(capabilities, bridge.session_id, opts)34 else35 raise CoreError, 'cannot understand dialect'36 end37 end38 # Override39 # Creates session handling both OSS and W3C dialects.40 # Copy from Selenium::WebDriver::Remote::Bridge to keep using `merged_capabilities` for Appium41 #42 # If `desired_capabilities` has `forceMjsonwp: true` in the capability, this bridge works with mjsonwp protocol.43 # If `forceMjsonwp: false` or no the capability, it depends on server side whether this bridge works as w3c or mjsonwp.44 #45 # @param [::Selenium::WebDriver::Remote::W3C::Capabilities, Hash] capabilities A capability46 # @return [::Selenium::WebDriver::Remote::Capabilities, ::Selenium::WebDriver::Remote::W3C::Capabilities]47 #48 # @example49 #50 # opts = {51 # caps: {52 # platformName: :ios,53 # automationName: 'XCUITest',54 # app: 'test/functional/app/UICatalog.app',55 # platformVersion: '10.3',56 # deviceName: 'iPhone Simulator',57 # useNewWDA: true,58 # forceMjsonwp: true59 # },60 # appium_lib: {61 # wait: 3062 # }63 # }64 # core = ::Appium::Core.for(caps)65 # driver = core.start_driver #=> driver.dialect == :oss66 #67 # @example68 #69 # opts = {70 # caps: {71 # platformName: :ios,72 # automationName: 'XCUITest',73 # app: 'test/functional/app/UICatalog.app',74 # platformVersion: '10.3',75 # deviceName: 'iPhone Simulator',76 # useNewWDA: true,77 # },78 # appium_lib: {79 # wait: 3080 # }81 # }82 # core = ::Appium::Core.for(caps)83 # driver = core.start_driver #=> driver.dialect == :w3c if the Appium server support W3C.84 #85 def create_session(desired_capabilities)86 response = execute(:new_session, {}, merged_capabilities(desired_capabilities))87 @session_id = response['sessionId']88 oss_status = response['status'] # for compatibility with Appium 1.7.1-89 value = response['value']90 if value.is_a?(Hash) # include for W3C format91 @session_id = value['sessionId'] if value.key?('sessionId')92 if value.key?('capabilities')93 value = value['capabilities']94 elsif value.key?('value')95 value = value['value']96 end97 end98 unless @session_id99 raise ::Selenium::WebDriver::Error::WebDriverError, 'no sessionId in returned payload'100 end101 json_create(oss_status, value)102 end103 # Append `appium:` prefix for Appium following W3C spec104 # https://www.w3.org/TR/webdriver/#dfn-validate-capabilities105 #106 # @param [::Selenium::WebDriver::Remote::W3C::Capabilities, Hash] capabilities A capability107 # @return [::Selenium::WebDriver::Remote::W3C::Capabilities]108 def add_appium_prefix(capabilities)109 w3c_capabilities = ::Selenium::WebDriver::Remote::W3C::Capabilities.new110 capabilities = capabilities.__send__(:capabilities) unless capabilities.is_a?(Hash)111 capabilities.each do |name, value|112 next if value.nil?...
patch.rb
Source: patch.rb
...60 def raw_execute(command, opts = {}, command_hash = nil)61 verb, path = Selenium::WebDriver::Remote::COMMANDS[command] ||62 fail(ArgumentError, "unknown command: #{command.inspect}")63 path = path.dup64 path[':session_id'] = @session_id if path.include?(':session_id')65 begin66 opts.each { |key, value| path[key.inspect] = escaper.escape(value.to_s) }67 rescue IndexError68 raise ArgumentError, "#{opts.inspect} invalid for #{command.inspect}"69 end70 # convert /// into /71 path.gsub!(/\/+/, '/')72 # change path from session/efac972c-941a-499c-803c-d7d008749/execute73 # to /execute74 # path may be nil, session, or not have anything after the session_id.75 path_str = path76 path_str = '/' + path_str unless path_str.nil? || path_str.length <= 0 || path_str[0] == '/'77 path_match = path.match(/.*\h{8}-?\h{4}-?\h{4}-?\h{4}-?\h{12}/)78 path_str = path.sub(path_match[0], '') unless path_match.nil?79 Appium::Logger.info "#{verb} #{path_str}"80 # must check to see if command_hash is a hash. sometimes it's not.81 if command_hash.is_a?(Hash) && !command_hash.empty?82 print_command = command_hash.clone83 print_command.delete :args if print_command[:args] == []84 if print_command[:using] == '-android uiautomator'85 value = print_command[:value].split(';').map { |v| "#{v};" }86 print_command[:value] = value.length == 1 ? value[0] : value87 # avoid backslash escape quotes in strings. "\"a\"" => "a"88 Appium::Logger.info print_command.ai.gsub('\"', '"')...
base.rb
Source: base.rb
...61 @default_javascript_framework = :prototype62 @highlight_located_element_by_default = false63 end64 @extension_js = ""65 @session_id = nil66 end67 def session_started?68 not @session_id.nil?69 end70 # Starts a new browser session (launching a new browser matching71 # configuration provided at driver creation time).72 #73 # Browser session specific option can also be provided. e.g.74 #75 # driver.start_new_browser_session(:captureNetworkTraffic => true)76 #77 def start_new_browser_session(options={})78 start_args = [@browser_string, @browser_url, @extension_js]79 if driver = options.delete(:driver)80 expected_browser_string = "*webdriver"81 unless @browser_string == expected_browser_string82 raise ArgumentError, "can't use :driver unless the browser string is #{expected_browser_string.inspect} (got #{@browser_string.inspect})"83 end84 sid = driver.capabilities['webdriver.remote.sessionid']85 sid or raise ArgumentError, "This driver can not be wrapped in the RC API."86 start_args << "webdriver.remote.sessionid=#{sid}"87 end88 start_args << options.collect {|key,value| "#{key.to_s}=#{value.to_s}"}.sort.join(";")89 @session_id = string_command "getNewBrowserSession", start_args90 # Consistent timeout on the remote control and driver side.91 # Intuitive and this is what you want 90% of the time92 self.remote_control_timeout_in_seconds = @default_timeout_in_seconds93 self.highlight_located_element = true if highlight_located_element_by_default94 end95 def close_current_browser_session96 remote_control_command "testComplete" if @session_id97 @session_id = nil98 end99 def start(opts = {})100 start_new_browser_session opts101 end102 def stop103 close_current_browser_session104 end105 def chrome_backend?106 ["*chrome", "*firefox", "*firefox2", "*firefox3"].include?(@browser_string)107 end108 def javascript_extension=(new_javascript_extension)109 @extension_js = new_javascript_extension110 end111 alias :set_extension_js :javascript_extension=...
env.rb
Source: env.rb
...43 browser.cookies.add 'mf_useformat', 'true'44 browser45end46def sauce_api(json, saucelabs_username, saucelabs_key)47 %x{curl -H 'Content-Type:text/json' -s -X PUT -d '#{json}' http://#{saucelabs_username}:#{saucelabs_key}@saucelabs.com/rest/v1/#{saucelabs_username}/jobs/#{$session_id}}48end49def sauce_browser(test_name, saucelabs_username, saucelabs_key, user_agent)50 config = YAML.load_file('config/config.yml')51 browser_label = config[ENV['BROWSER_LABEL']]52 if user_agent == 'default'53 caps = Selenium::WebDriver::Remote::Capabilities.send(browser_label['name'])54 else browser_label['name'] == 'firefox'55 profile = Selenium::WebDriver::Firefox::Profile.new56 profile['general.useragent.override'] = user_agent57 caps = Selenium::WebDriver::Remote::Capabilities.firefox(:firefox_profile => profile)58 end59 caps.platform = browser_label['platform']60 caps.version = browser_label['version']61 caps[:name] = "#{test_name} #{ENV['JOB_NAME']}##{ENV['BUILD_NUMBER']}"62 require 'selenium/webdriver/remote/http/persistent' # http_client63 browser = Watir::Browser.new(64 :remote,65 http_client: Selenium::WebDriver::Remote::Http::Persistent.new,66 url: "http://#{saucelabs_username}:#{saucelabs_key}@ondemand.saucelabs.com:80/wd/hub",67 desired_capabilities: caps)68 browser.wd.file_detector = lambda do |args|69 # args => ['/path/to/file']70 str = args.first.to_s71 str if File.exist?(str)72 end73 browser74end75def test_name(scenario)76 if scenario.respond_to? :feature77 "#{scenario.feature.name}: #{scenario.name}"78 elsif scenario.respond_to? :scenario_outline79 "#{scenario.scenario_outline.feature.name}: #{scenario.scenario_outline.name}: #{scenario.name}"80 end81end82config = YAML.load_file('config/config.yml')83mediawiki_username = config['mediawiki_username']84secret = YAML.load_file('/private/wmf/secret.yml')85mediawiki_password = secret['mediawiki_password']86saucelabs_username = secret['saucelabs_username']87saucelabs_key = secret['saucelabs_key']88Before('@user_agent') do |scenario|89 @user_agent = true90 @saucelabs_username = saucelabs_username91 @saucelabs_key = saucelabs_key92 @scenario = scenario93end94Before do |scenario|95 @config = config96 @mediawiki_username = mediawiki_username97 @mediawiki_password = mediawiki_password98 unless @user_agent99 @browser = browser(environment, test_name(scenario), saucelabs_username, saucelabs_key, 'default') unless @user_agent100 $session_id = @browser.driver.instance_variable_get(:@bridge).session_id101 end102end103After do |scenario|104 $session_id = @browser.driver.instance_variable_get(:@bridge).session_id105 if environment == :cloudbees106 sauce_api(%Q{{"passed": #{scenario.passed?}}}, saucelabs_username, saucelabs_key)107 sauce_api(%Q{{"public": true}}, saucelabs_username, saucelabs_key)108 end109 @browser.close unless ENV['KEEP_BROWSER_OPEN'] == 'true'110end...
driver_helper.rb
Source: driver_helper.rb
...62 # current session is a wrapper of Capybara::Selenium::Driver,63 # Capybara::Selenium::Driver instantiates a browser from Selenium::Webdriver64 # then bridge is a private method in Selenium::Webdriver::Driver65 bridge = Capybara.current_session.driver.browser.send :bridge66 session_id = bridge.session_id67 Autospec.logger.debug "bridge session_id: #{session_id}"68 http_auth = "https://#{self.user}:#{self.pass}@saucelabs.com/rest/v1/#{self.user}/jobs/#{session_id}"69 # to_json need to: require "active_support/core_ext", but will mess up the whole framework, require 'json' in this method solved it70 body = {"name" => new_name, "tags" => [new_tags]}.to_json71 # gem 'rest-client'72 Autospec.logger.debug "About to send request to saucelabs with url as #{http_auth} and body as #{body}"73 RestClient.put(http_auth, body, {:content_type => "application/json"})74 end75 end76end...
selenium.rb
Source: selenium.rb
...55 raw_driver.file_detector = lambda do |args|56 file_path = args.first.to_s57 File.exist?(file_path) ? file_path : false58 end59 Sauce.logger.debug "Thread #{Thread.current.object_id} created driver #{raw_driver.session_id}"60 Sauce::Selenium2.used_at_least_once61 end62 def method_missing(meth, *args)63 raw_driver.send(meth, *args)64 end65 def session_id66 raw_driver.send(:bridge).session_id67 end68 def current_url69 raw_driver.current_url70 end71 def stop72 Sauce.logger.debug "Thread #{Thread.current.object_id} quitting driver #{@driver.session_id}"73 quit_and_maybe_rescue @driver74 Sauce.logger.debug "Thread #{Thread.current.object_id} has quit driver #{@driver.session_id}"75 end76 def quit77 quit_and_maybe_rescue raw_driver78 end79 def quit_and_maybe_rescue driver80 begin81 driver.quit82 rescue Selenium::WebDriver::Error::WebDriverError => e 83 session_finished = e.message.match "has already finished, and can't receive further commands"84 unless @config[:suppress_session_quit_failures] && session_finished85 raise e86 end 87 end88 end...
spec_helper.rb
Source: spec_helper.rb
...17 end18 config.after(:each) do19 if ENV['host'] != 'localhost'20 if example.exception.nil?21 SauceWhisk::Jobs.pass_job @driver.session_id22 else23 SauceWhisk::Jobs.fail_job @driver.session_id24 end25 end26 @driver.quit27 end28end...
session_id
Using AI Code Generation
1driver.find_element(:name, 'q').send_keys "Selenium WebDriver"2driver.find_element(:name, 'btnG').click3driver.find_element(:name, 'q').send_keys "Selenium WebDriver"4driver.find_element(:name, 'btnG').click
session_id
Using AI Code Generation
1driver = Selenium::WebDriver.for(:remote, url: 'http://localhost:4444/wd/hub', desired_capabilities: :chrome)2driver.navigate.to('http://google.com')3driver = Selenium::WebDriver.for(:remote, url: 'http://localhost:4444/wd/hub', desired_capabilities: :chrome)4driver.navigate.to('http://google.com')5driver = Selenium::WebDriver.for(:remote, url: 'http://localhost:4444/wd/hub', desired_capabilities: :chrome)6driver.navigate.to('http://google.com')7driver = Selenium::WebDriver.for(:remote, url: 'http://localhost:4444/wd/hub', desired_capabilities: :chrome)8driver.navigate.to('http://google.com')9driver = Selenium::WebDriver.for(:remote, url: 'http://localhost:4444/wd/hub', desired_capabilities: :chrome)10driver.navigate.to('http://google.com')11driver = Selenium::WebDriver.for(:remote, url: 'http://localhost:4444/wd/hub', desired_capabilities: :chrome)12driver.navigate.to('http://google.com')13driver = Selenium::WebDriver.for(:remote, url: 'http://localhost:4444/wd/hub
session_id
Using AI Code Generation
1File.open("session_id.txt", "w") {|f| f.write(session_id) }2File.open("session_id.txt", "w") {|f| f.write(session_id) }3File.open("session_id.txt", "w") {|f| f.write(session_id) }4File.open("session_id.txt", "w") {|f| f.write(session_id) }5File.open("session_id.txt", "w") {|f| f.write(session_id) }6File.open("session_id.txt", "w") {|f| f.write(session_id) }7File.open("session_id.txt", "w") {|f| f.write(session_id) }8File.open("session_id.txt", "w") {|f| f.write(session_id) }9File.open("session_id.txt", "w") {|f| f.write(session_id) }
Unsupported command-line flag: --ignore-certificate-errors (in Ruby)
Enter password in dialog/prompt
How to setup Capybara with Safari Technology Preview in Ruby
Can you close all open windows in capybara?
remove alert confirms javascript with watir webdriver
Wrap each command in a rescue statement
Why am I not able to login to Quora using an automation package like Selenium or Watir?
Iterate through all form fields with selenium in ruby
ruby selenium xpath td css
Capybara headless download
The Ruby selenium-webdriver API doesn't expose a separate Chrome options object like Java/Python but you can set the options via "Capabilities".
The Capabilities web page provides a Ruby example and the table of recognized capabilities that you can inject. Plugging those together with excludeSwitches
:
caps = Selenium::WebDriver::Remote::Capabilities.chrome("chromeOptions" => {"excludeSwitches" => [ "--ignore-certificate-errors" ]})
driver = Selenium::WebDriver.for :chrome, desired_capabilities: caps
Take a look at Watir too, it's a front end for WebDriver.
Their examples show how you can send a :switches
array which is passed straight through to the web driver so you can do the same. That makes adding other switches a bit easier rather than going through capabilities.
There is a chromedriver issue on the topic as well. There are posts detailing that you can add a --test-type
argument to work around the certificate issue and ruby code examples like above.
Check out the latest blogs from LambdaTest on this topic:
We have all been in situations while using a software or a web application, everything is running too slow. You click a button and nothing is happening except a loader animation spinning for an infinite time.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium Python Tutorial.
We love PWAs and seems like so do you ???? That’s why you are here. In our previous blogs, Testing a Progressive web app with LambdaTest and Planning to move your app to a PWA: All you need to know, we have already gone through a lot on PWAs so we decided to cut is short and make it easier for you to memorize by making an Infographic, all in one place. Hope you like it.
The necessity for vertical text-orientation might not seem evident at first and its use rather limited solely as a design aspect for web pages. However, many Asian languages like Mandarin or Japanese scripts can be written vertically, flowing from right to left or in case of Mongolian left to right. In such languages, even though the block-flow direction is sideways either left to right or right to left, letters or characters in a line flow vertically from top to bottom. Another common use of vertical text-orientation can be in table headers. This is where text-orientation property becomes indispensable.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium JavaScript Tutorial.
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!