简体   繁体   中英

Ruby Selenium begin rescue

I use Cucumber with Ruby and Selenium. Here is scenario where I need to check that element is not on the page When I do such within Cucumber step

    Step file:
    begin
     expect(checkout_page.city_acctdetails.displayed?).to eql false
    rescue Selenium::WebDriver::Error::NoSuchElementError
     puts "City dropdown is not present"
     false
    end

it works like a charm. When I try to do something like by putting as method in another file/helper

 RubyHelper.rb file
   def self.not_present(locator)
    begin
      locator.displayed?
    rescue Selenium::WebDriver::Error::NoSuchElementError
      puts "Not present"
      false
    end
  end

so when I change in Cucumber Step file

RubyHelper.not_present(checkout_page.city_acctdetails)

I get error: Unable to locate element: {} (Selenium::WebDriver::Error::NoSuchElementError)

Require statements:

  #BDD framework that makes feature files running
require 'cucumber'

#Control remote browsers
require 'selenium-webdriver'

#Run tests in parallel
require 'parallel_tests'

#Use expect().to for verifying result
require 'rspec'

#Key value format for storing text data
require 'yaml'

Ruby Cucumber magic depends on something called the World object . To make your RubyHelper file available to your step definitions you need to:

  1. Wrap the helper methods in a module
  2. Tell Cucumber to include the module into each World object for each Scenario

RubyHelper.rb file

require 'cucumber'
require 'selenium-webdriver'
require 'rspec'
module MyHelper
  def not_present(locator)
    begin
      locator.displayed?
    rescue Selenium::WebDriver::Error::NoSuchElementError
      puts "Not present"
      false
    end
  end
end
World(MyHelper)

Maybe you can try to sleep or wait for that event load. It something that when you run your test, the test was executed but the element is not yet there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM