Exception handling issue in ruby - ruby

In the following code i want to handle the exception.if msg[0] not found i have to catch that exception message msg[2] in rescue and if it is found put the success message msg[1]
puts "Verifying Home Page"
def verifyHomepage(*args)
begin
args.each do |msg|
page.find(msg[0])
puts msg[1]
rescue
puts msg[2]
end
end
end
verifyHomepage(['#logoAnchorr', 'logo anchor found', 'Logo anchor not Found'], ['.navbar-inner', 'Header Bar found', 'Header Bar not Found'])
In the above code iam getting
error sysntax error unexpected keyword rescue expecting keyword end

Salil has pointed you where to fix,that's correct. Now The below approach also you could adapt:
puts "Verifying Home Page"
def verifyHomepage(*args)
args.each do |msg|
next puts(msg[1]) if page.find(msg[0]) rescue nil
puts msg[2]
end
end
a = [['#logoAnchorr', 'logo anchor found', 'Logo anchor not Found'], ['.navbar-inner', 'Header Bar found', 'Header Bar not Found']]
verifyHomepage(*a)
Output:
Verifying Home Page
Logo anchor not Found
Header Bar not Found

You have to write begin inside the block
puts "Verifying Home Page"
def verifyHomepage(*args)
args.each do |msg|
begin
page.find(msg[0])
puts msg[1]
rescue
puts msg[2]
end
end
end
verifyHomepage(['#logoAnchorr', 'logo anchor found', 'Logo anchor not Found'], ['.navbar-inner', 'Header Bar found', 'Header Bar not Found'])

Related

How to expect Capybara::Expectation for a method

def tiltle_finder(names)
within 'table tbody tr:nth-child(1)' do
page.should have_selector(
'td:nth-child(10)',
text: "#{names.label}"
)
end
end
it 'should find title' do
expect{
tiltle_finder(names)
}.to raise_error(Capybara::ExpectationNotMet)
but still trows that exception
Capybara::ExpectationNotMet
Instead of rescuing error you may just check that expectations are not met:
def have_title_finder(names)
within 'table tbody tr:nth-child(1)' do
have_selector(
'td:nth-child(10)',
text: "#{names.label}"
)
end
end
# ...
expect(page).not_to have_title_finder(names)
def tiltle_finder(names)
within 'table tbody tr:nth-child(1)' do
page.find('td:nth-child(10)', text: "#{names.label}")
end
end
it 'should find title' do
expect{
tiltle_finder(names)
}.to raise_error(Capybara::ElementNotFound)
end
Solved as this

Ruby code not executed after method call

Code is not executed (puts "hey") in the harvest method after the call to searchEmails(page). I'm probably missing something simple with Ruby because I'm just getting back into it.
def searchEmails(page_to_search)
begin
html = #agent.get(url).search('html').to_s
mail = html.scan(/['.'\w|-]*#+[a-z]+[.]+\w{2,}/).map.to_a
base = page_to_search.uri.to_s.split("//", 2).last.split("/", 2).first
mail.each{|e| #file.puts e+";"+base unless e.include? "example.com" or e.include? "email.com" or e.include? "domain.com" or e.include? "company.com" or e.length < 9 or e[0] == "#"}
end
end
def harvest(url)
begin
page = #agent.get(url)
searchEmails(page)
puts "hey"
rescue Exception
end
end
url="www.example.com"
harvest(url)
#agent.get(url) will fail with a bad url or network outage.
The problem in your code could be written as follows:
def do_something
begin
raise
puts "I will never get here!"
rescue
end
end
Since you can't get rid of the raise, you need to do something inside the rescue (most likely log it):
begin
#agent.get(url)
# ...
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError,
Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError,
Net::ProtocolError => e
log(e.message, e.callback)
end

How to test whether an element is displayed on the page

The following code checks whether an element is displayed and if the element is present runs a specific action, else the test continues normally:
require "selenium-webdriver"
require "rspec"
require 'rspec/expectations'
describe "Current Expense" do
before(:all) do
#driver = Selenium::WebDriver.for :firefox
#base_url = "http://the-internet.herokuapp.com/disappearing_elements"
#driver.manage.window.maximize
end
after(:all) do
#driver.quit
end
it "Check icon" do
#driver.get(#base_url)
if expect(#driver.find_element(:xpath, "//*[#href='/gallery/']").displayed?).to be_truthy
#driver.find_element(:xpath, "//*[#href='/gallery/']").click
sleep 2
puts "element appears"
else
puts "element NOT appears"
end
end
end
When the element is present, the message appears, but when the element is not present in the page, an error occurs and the else block is not executed. What is causing this error?
I think the problem is that you're using expect when you should just have the conditional #driver.find_element(:xpath, "//*[#href='/gallery/']").displayed?. If the conditional is true you will see the expected message; likewise if it evaluates to false you will see `"element NOT appears".
As currently constructed, if the find_element method returns false then the spec should fail. Please post the error or exception you're seeing so that we can know for sure.
On a side note, what you have right now is fine for a quick and dirty test of whether or not the page is functioning correctly, but you'll probably want to give two cases in your test file: one where you know the icon will be on the page, and one where it shouldn't be on the page, and then test the outcome for each. For example:
#Code omitted
it "has the icon when x is the case" do
# make x be the case
#driver.get(#base_url)
#driver.find_element(:xpath, "//*[#href='/gallery/']").displayed?
#driver.find_element(:xpath, "//*[#href='/gallery/']").click
sleep 2
# code that verifies that the element is on the page
end
it "doesn't have the icon when y is the case" do
# make y be the case
#driver.get(#base_url)
expect {
#driver.find_element(:xpath, "//*[#href='/gallery/']").displayed?
}.to be_false
end
#code omitted
expect is the reason for test failure. Find the below snippet for solution.. Cheers!
it "has the icon when x is the case" do
#driver.get(#base_url)
begin
#driver.find_element(:xpath, "//*[#href='/gallery/']")
#driver.find_element(:xpath, "//*[#href='/gallery/']").click
rescue Selenium::WebDriver::Error::NoSuchElementError
raise 'The Element ' + what + ' is not available'
end
end
it "doesn't have the icon when y is the case" do
#driver.get(#base_url)
begin
#driver.find_element(:xpath, "//*[#href='/gallery/']")
raise 'The Element ' + what + ' is available'
rescue Selenium::WebDriver::Error::NoSuchElementError
expect(true).to be_truthy
end
end

Call yield from another do ...end block

I try to define own 'context' method in Rspec.
Have next:
module MiscSpecHelper
def its_ok
context "if everything is OK" do
yield
end
end
end
in spec file:
describe "GET index" do
its_ok do
it "has a 200 status code" do
get :index
expect(response.status).to eq(200)
end
end
end
I got:
GET index
has a 200 status code
I expect:
GET index
if everything is OK
has a 200 status code
Why does it ignore my 'context' description?
module MiscSpecHelper
def its_ok(&block)
context "if everything is OK", &block
end
end

How to test adding line to error log by causing rescue statement in rspec

I have a this Foo class.
class Foo
def open_url
Net::HTTP.start("google.com") do |http|
# Do Something
end
rescue Exception => e
File.open("error.txt","a+"){|f| f.puts e.message }
end
end
And I want to test by this Rspec.
require_relative 'foo'
describe Foo do
describe "#open_url" do
it "should put error log if connection fails" do
Net::HTTP.stub(:start).and_return(Exception)
# Check if a line to error.txt is added.
end
end
end
How can I check if a line is inserted to error.txt?
You could read the file you are actually writing
describe Foo do
describe "#open_url" do
it "should put error log if connection fails" do
Net::HTTP.stub(:start).and_raise
Foo.open_url
file = File.open("error.txt", "r")
# ...
end
end
end
An alternative would be to check that the file is opened: something along the lines of this
File.should_receive(:open).with("error.txt", "a+", {|f| f.puts e.message })

Resources