module Browsery::Utils::Castable::ClassMethods

Public Instance Methods

cast(driver, name) click to toggle source

Attempts to create a new page object from a driver state. Use the instance method for convenience. Raises `NameError` if the page could not be found.

@param driver [Selenium::WebDriver] The instance of the current

WebDriver.

@param name [#to_s] The name of the page object to instantiate. @return [Base] A subclass of `Base` representing the page object. @raise InvalidPageState if the page cannot be casted to @raise NameError if the page object doesn't exist

# File lib/browsery/utils/castable.rb, line 19
def cast(driver, name)
  # Transform the name string into a file path and then into a module name
  klass_name = "browsery/page_objects/#{name}".camelize

  # Attempt to load the class
  klass = begin
    klass_name.constantize
  rescue => exc
    msg = ""
    msg << "Cannot find page object '#{name}', "
    msg << "because could not load class '#{klass_name}' "
    msg << "with underlying error:\n  #{exc.class}: #{exc.message}\n"
    msg << exc.backtrace.map { |str| "    #{str}" }.join("\n")
    raise NameError, msg
  end

  # Instantiate the class, passing the driver automatically, and
  # validates to ensure the driver is in the correct state
  instance = klass.new(driver)
  begin
    instance.validate!
  rescue Minitest::Assertion => exc
    raise Browsery::PageObjects::InvalidePageState, "#{klass}: #{exc.message}"
  end
  instance
end