NoMethodError: private method `browser_name' called for {:browserName=>:firefox, :version=>nil}:Hash - ruby

I am trying to learn selenium Grid, I followed a tutorial, but when I try to run my feature I got this error :
NoMethodError: private method `browser_name' called for {:browserName=>:firefox, :version=>nil}:Hash
here is the env.rb file :
require 'watir-webdriver'
require 'cucumber'
def browser_path
(ENV['BPATH'])
end
def browser_name
(ENV['BROWSER'] ||= 'firefox').downcase.to_sym
end
def environment
(ENV['ENV'] ||= 'grid').downcase.to_sym
end
def browser_version
(ENV['VER'])
end
Before do
def assert_it message, &block
begin
if (block.call)
puts "Assertion PASSED for #{message}"
else
puts "Assertion FAILED for #{message}"
fail('Test Failure on assertion')
end
rescue => e
puts "Assertion FAILED for #{message} with exception '#{e}'"
fail('Test Failure on assertion')
end
end
if browser_path != nil
Selenium::WebDriver::Firefox.path= "#{browser_path}"
end
if environment == :grid
#browser = Watir::Browser.new(:remote, :url=>"http://10.196.60.38:4444/wd/hub", :desired_capabilities=> {browserName: browser_name,version: browser_version})
#browser.window.maximize
else
#browser = Watir::Browser.new browser_name
#browser.window.maximize
end
end
After do
#browser.close
end
Thanks, your help is appreciated.

watir-webdriver is deprecated and will not work with latest versions of Firefox. Please update to the latest version of watir.
Also with latest version of watir, you should be able to just do:
Watir::Browser.new(browser_name, url: "http://10.196.60.38:4444/wd/hub", version: browser_version

Related

ruby undefined method string for TempFile?

I have been trying to use the ticketmaster api to obtain some data. However, it throws an error when I try to run the code. I do not know why the error is popping up. I do not know if it is because of the url that I gave. Open method accept the url as string so I converted to string and this url is working in postman if I try. The exact error is
C:/RailsInstaller/Ruby2.3.0/lib/ruby/2.3.0/delegate.rb:87:in `method_missing': u
ndefined method `string' for #<Tempfile:0x28c2d50> (NoMethodError)
from test.rb:20:in `connection'
from test.rb:47:in `<main>'
and my code is ;
require 'open-uri'
require 'openssl'
require 'json'
class Test
#silence_warnings do
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE #unless Rails.env.production?
#end
def initialize()
#url="https://app.ticketmaster.com/discovery/v2/events.json?apikey=XXXXXXXXXXXXXXXXXT&city=Binghamton"
end
def connection
puts "url", #url
result=open(#url)
response_status=result.status
#putstus
if(response_status[0]=="200")
#body=JSON.parse(result.string)
puts("Status is "+ response_status[0],"Server Message is "+ response_status[1])
return #body
else
connection_error
puts("Status is ", response_status[0])
end
end
def connection_error
puts "Connection error with the api"
end
def silence_warnings
with_warnings(nil) { yield }
end
def get_content
raise notImplementedMethod
end
end
a=Test.new
a.connection

API integration error HTTParty

I'm learning how to work with HTTParty and API and I'm having an issue with my code.
Users/admin/.rbenv/versions/2.0.0-p481/lib/ruby/2.0.0/uri/generic.rb:214:in `initialize': the scheme http does not accept registry part: :80 (or bad hostname?)
I've tried using debug_output STDOUT both as an argument to my method and after including HTTParty to have a clue but with no success. Nothing gets displayed:
require 'httparty'
class LolObserver
include HTTParty
default_timeout(1) #timeout after 1 second
attr_reader :api_key, :playerid
attr_accessor :region
def initialize(region,playerid,apikey)
#region = region_server(region)
#playerid = playerid
#api_key = apikey
end
def region_server(region)
case region
when "euw"
self.class.base_uri "https://euw.api.pvp.net"
self.region = "EUW1"
when "na"
self.class.base_uri "https://na.api.pvp.net"
self.region = "NA1"
end
end
def handle_timeouts
begin
yield
#Timeout::Error, is raised if a chunk of the response cannot be read within the read_timeout.
#Timeout::Error, is raised if a connection cannot be created within the open_timeout.
rescue Net::OpenTimeout, Net::ReadTimeout
#todo
end
end
def base_path
"/observer-mode/rest/consumer/getSpectatorGameInfo"
end
def current_game_info
handle_timeouts do
url = "#{ base_path }/#{region}/#{playerid}?api_key=#{api_key}"
puts '------------------------------'
puts url
HTTParty.get(url,:debug_output => $stdout)
end
end
end
I verified my URL which is fine so I'm lost as to where the problem is coming from.
I tested with a static base_uri and it doesn't change anything.
The odd thing is when I do:
HTTParty.get("https://euw.api.pvp.net/observer-mode/rest/consumer/getSpectatorGameInfo/EUW1/randomid?api_key=myapikey")
Everything is working fine and I'm getting a response.
HTTParty doesn't seem to like the way you set your base_uri.
Unless you need it to be like that just add another attr_reader called domain and it will work.
require 'httparty'
class LolObserver
include HTTParty
default_timeout(1) #timeout after 1 second
attr_reader :api_key, :playerid, :domain
attr_accessor :region
def initialize(region,playerid,apikey)
#region = region_server(region)
#playerid = playerid
#api_key = apikey
end
def region_server(region)
case region
when "euw"
#domain = "https://euw.api.pvp.net"
self.region = "EUW1"
when "na"
#domain = "https://na.api.pvp.net"
self.region = "NA1"
end
end
def handle_timeouts
begin
yield
#Timeout::Error, is raised if a chunk of the response cannot be read within the read_timeout.
#Timeout::Error, is raised if a connection cannot be created within the open_timeout.
rescue Net::OpenTimeout, Net::ReadTimeout
#todo
end
end
def base_path
"/observer-mode/rest/consumer/getSpectatorGameInfo"
end
def current_game_info
handle_timeouts do
url = "#{domain}/#{ base_path }/#{region}/#{playerid}?api_key=#{api_key}"
puts '------------------------------'
puts url
HTTParty.get(url,:debug_output => $stdout)
end
end
end

Ruby: Chatterbot can't load bot data

I'm picking up ruby language and get stuck at playing with the chatterbot i have developed. Similar issue has been asked here Click here , I did what they suggested to change the rescue in order to see the full message.But it doesn't seem right, I was running basic_client.rb at rubybot directory and fred.bot is also generated at that directory . Please see the error message below: Your help very be very much appreciated.
Snailwalkers-MacBook-Pro:~ snailwalker$ cd rubybot
Snailwalkers-MacBook-Pro:rubybot snailwalker$ ruby basic_client.rb
/Users/snailwalker/rubybot/bot.rb:12:in `rescue in initialize': Can't load bot data because: No such file or directory - bot_data (RuntimeError)
from /Users/snailwalker/rubybot/bot.rb:9:in `initialize'
from basic_client.rb:3:in `new'
from basic_client.rb:3:in `<main>'
basic_client.rb
require_relative 'bot.rb'
bot = Bot.new(:name => 'Fred', :data_file => 'fred.bot')
puts bot.greeting
while input = gets and input.chomp != 'end'
puts '>> ' + bot.response_to(input)
end
puts bot.farewell
bot.rb:
require 'yaml'
require './wordplay'
class Bot
attr_reader :name
def initialize(options)
#name = options[:name] || "Unnamed Bot"
begin
#data = YAML.load(File.read('bot_data'))
rescue => e
raise "Can't load bot data because: #{e}"
end
end
def greeting
random_response :greeting
end
def farewell
random_response :farewell
end
def response_to(input)
prepared_input = preprocess(input).downcase
sentence = best_sentence(prepared_input)
reversed_sentence = WordPlay.switch_pronouns(sentence)
responses = possible_responses(sentence)
responses[rand(responses.length)]
end
private
def possible_responses(sentence)
responses = []
#data[:responses].keys.each do |pattern|
next unless pattern.is_a?(String)
if sentence.match('\b' + pattern.gsub(/\*/, '') + '\b')
if pattern.include?('*')
responses << #data[:responses][pattern].collect do |phrase|
matching_section = sentence.sub(/^.*#{pattern}\s+/, '')
phrase.sub('*', WordPlay.switch_pronouns(matching_section))
end
else
responses << #data[:responses][pattern]
end
end
end
responses << #data[:responses][:default] if responses.empty?
responses.flatten
end
def preprocess(input)
perform_substitutions input
end
def perform_substitutions(input)
#data[:presubs].each {|s| input.gsub!(s[0], s[1])}
input
end
# select best_sentence by looking at longest sentence
def best_sentence(input)
hot_words = #data[:responses].keys.select do |k|
k.class == String && k =~ /^\w+$/
end
WordPlay.best_sentence(input.sentences, hot_words)
end
def random_response(key)
random_index = rand(#data[:responses][key].length)
#data[:responses][key][random_index].gsub(/\[name\]/, #name)
end
end
I'm assuming that you are trying to load the :data_file passed into Bot.new, but right now you are statically loading a bot_data file everytime. You never mentioned about bot_data in the question. So if I'm right it should be like this :
#data = YAML.load(File.read(options[:data_file]))
Instead of :
#data = YAML.load(File.read('bot_data'))

Why browser.text.include? produces error in Watir Ruby script

Issue: I have researched online on how to verify if text exists on my page, but I keep getting error messages. I have attempted using "expect" and one without "expect". For something that seems basic, I am not sure why this is not asserting correctly.
Ruby File:
require "rubygems"
require "watir-webdriver"
require "rspec"
require "selenium-webdriver"
require "rspec/expectations"
#browser = Watir::Browser.new :internet_explorer
begin
if expect(#browser.text.include?("Welcome")).to be_true
##browser.text.include?("Welcome").should == true
puts "Test passed!"
else
puts "Test failed!"
end
end
Error:
test2.rb:61:in <main>': undefined methodexpect' for main:Object (NoMethodError)
You should have your expectations defined inside a test case
describe "IE" do
it "should have test 'Welcome'" do
expect(#browser.text.include("Welcome")).to be_true
end
end
Or if you just want your script to print pass or fail, just do
begin
if #browser.text.include?("Welcome")
puts "Test passed!"
else
puts "Test failed!"
end
end

Selenium WebDriver for ruby fails with "too many redirects"

I've got this simple test case that tests a login form.
For some reason webdriver refuses to run the test and comes back with a "too many redirects" message. The page is just an ordinary login screen, very simple and there are no redirects whatsoever. Access from the server to the page seems ok.
I'm using selenium-webdriver-2.25.0 on a centos server.
Below the error message:
(...)
[WARNING] MultiJson is using the default adapter (ok_json). We recommend loading a different JSON library to improve performance.
EE
Finished in 0.206445 seconds.
1) Error: test_login(Login):
Selenium::WebDriver::Error::WebDriverError: too many redirects
/usr/lib/ruby/gems/1.8/gems/selenium-webdriver-2.25.0/lib/selenium/webdriver/remote/http/default.rb:62:in `request'
/usr/lib/ruby/gems/1.8/gems/selenium-webdriver-2.25.0/lib/selenium/webdriver/remote/http/default.rb:63:in `request'
/usr/lib/ruby/gems/1.8/gems/selenium-webdriver-2.25.0/lib/selenium/webdriver/remote/http/common.rb:40:in `call'
(...)
My code:
require "rubygems"
require "selenium-webdriver"
require "test/unit"
class Login < Test::Unit::TestCase
def setup
#driver =Selenium::WebDriver.for(:remote, :url => "http://selenium.server.com/wd/hub")
#base_url = "http://www.myservice.com"
#driver.manage.timeouts.implicit_wait = 30
#verification_errors = []
end
def teardown
#driver.quit
assert_equal [], #verification_errors
end
def test_login
#driver.get(#base_url + "/login/")
#driver.find_element(:id, "username").clear
#driver.find_element(:id, "username").send_keys "user#server"
#driver.find_element(:id, "password").clear
#driver.find_element(:id, "password").send_keys "mykeys!"
#driver.find_element(:xpath, "//input[#value='Login']").click
verify { assert element_present?(:link, "Logout") }
verify { assert element_present?(:link, "Settings") }
verify { assert element_present?(:link, "Products") }
end
def element_present?(how, what)
#driver.find_element(how, what)
true
rescue Selenium::WebDriver::Error::NoSuchElementError
false
end
def verify(&blk)
yield
rescue Test::Unit::AssertionFailedError => ex
#verificatiohttp://jenkins.dev.emesa-auctions.com/cms/n_errors << ex
end
end
UPDATE
It seems that no matter what url I use for the 'base url' the errors keeps occuring.
I managed to solve this problem myself. The issue was that I was accessing the server through its public facing url (selenium.server.com) instead of through the internal lan url (which bypass the firewall).
Changing that fixed the problem.

Resources