Just do change as below
def click_on_product(fruit)
index = index_for(fruit)
begin
# will throw type error, when index is nil.
fruits_element[index].link_element.click
rescue TypeError => ex
# any exception related message if you want to print
# should be here.
end
end
However when the index returns nil, it clicks on the link for element 0. Is there a proper way to fail this?
See, you used index.to_i
, in the line fruits_element[index.to_i].link_element.click
. Now, NilClass#to_i
method, actually returning 0
. Because nil.to_i
is 0
. Thus fruits_element[index.to_i]
is actually became fruits_element[0]
, which is the first element, that was getting click as you reported.
As you want to raise error, just don't use to_i
method there.
find_index
method either returns integer when found, or nil
when not found. I think as per your code, there is no need to convert an integer to again integer, as you are interested to throw error.
You should also write the method index_for
as below.
def index_for(fruit)
fruits_elements.find_index {|f| f.div_element.text == fruit }
end
You don't need to write the variable index
as a last expression to return it. Because in Ruby, last expression of a method by default returned.