diff --git a/lib/webcat.rb b/lib/webcat.rb index 13a795a6..7c01ff4f 100644 --- a/lib/webcat.rb +++ b/lib/webcat.rb @@ -3,6 +3,7 @@ module Webcat class WebcatError < StandardError; end class DriverNotFoundError < WebcatError; end + class ElementNotFound < WebcatError; end class << self attr_accessor :debug diff --git a/lib/webcat/session.rb b/lib/webcat/session.rb index b80eaaab..e4bb8bdd 100644 --- a/lib/webcat/session.rb +++ b/lib/webcat/session.rb @@ -22,13 +22,21 @@ class Webcat::Session end def click_link(locator) - link = driver.find("//a[@id='#{locator}']").first - link ||= driver.find(%{//a[text()="#{locator}"]}).first - link ||= driver.find(%{//a[@title="#{locator}"]}).first - link.click + find_element("//a[@id='#{locator}']", %{//a[text()="#{locator}"]}, %{//a[@title="#{locator}"]}).click end def body driver.body end + +private + + def find_element(*locators) + locators.each do |locator| + element = driver.find(locator).first + return element if element + end + raise Webcat::ElementNotFound, "element not found" + end + end diff --git a/spec/session_spec.rb b/spec/session_spec.rb index d3b9ce0b..177ea30e 100644 --- a/spec/session_spec.rb +++ b/spec/session_spec.rb @@ -18,9 +18,12 @@ describe Webcat::Session do end describe '#click_link' do + before do + @session.visit('/with_html') + end + context "with id given" do it "should take user to the linked page" do - @session.visit('/with_html') @session.click_link('foo') @session.body.should == 'Another World' end @@ -28,7 +31,6 @@ describe Webcat::Session do context "with text given" do it "should take user to the linked page" do - @session.visit('/with_html') @session.click_link('labore') @session.body.should == '

Bar

' end @@ -36,11 +38,18 @@ describe Webcat::Session do context "with title given" do it "should take user to the linked page" do - @session.visit('/with_html') @session.click_link('awesome title') @session.body.should == '

Bar

' end end + + context "with a locator that doesn't exist" do + it "should raise an error" do + running do + @session.click_link('does not exist') + end.should raise_error(Webcat::ElementNotFound) + end + end end end