只需进行如下更改
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
但是,当索引返回 nil 时,它会单击元素 0 的链接。是否有正确的方法来失败?
看,你index.to_i
在行中使用了 , fruits_element[index.to_i].link_element.click
。现在,NilClass#to_i
方法,实际上返回0
. 因为nil.to_i
是0
。因此fruits_element[index.to_i]
实际上变成fruits_element[0]
了,这是第一个元素,正如您所报告的那样获得点击。
当你想引发错误时,不要to_i
在那里使用方法。
find_index
方法要么在找到时返回整数,要么nil
在未找到时返回。我认为根据您的代码,没有必要将整数再次转换为整数,因为您有兴趣抛出错误。
您还应该编写如下方法index_for
。
def index_for(fruit)
fruits_elements.find_index {|f| f.div_element.text == fruit }
end
您不需要将变量写index
为最后一个表达式来返回它。因为在 Ruby 中,默认返回方法的最后一个表达式。