Search code examples
rubycucumbermechanizewebratmechanize-ruby

How to set a "base URL" for Webrat, Mechanize


I would like to specify a base URL so I don't have to always specify absolute URLs. How can I specify a base URL for Mechanize to use?


Solution

  • To accomplish the previously proffered answer using Webrat, you can do the following e.g. in your Cucumber env.rb:

    require 'webrat'
    
    Webrat.configure do |config|
      config.mode = :mechanize
    end
    
    World do
      session = Webrat::Session.new
      session.extend(Webrat::Methods)
      session.extend(Webrat::Matchers)
      session.visit 'http://yoursite/yourbasepath/'
      session
    end
    

    To make it more robust, such as for use in different environments, you could do:

    ENV['CUCUMBER_HOST'] ||= 'yoursite'
    ENV['CUCUMBER_BASE_PATH'] ||= '/yourbasepath/'
    
    # Webrat
    require 'webrat'
    
    Webrat.configure do |config|
      config.mode = :mechanize
    end
    
    World do
      session = Webrat::Session.new
      session.extend(Webrat::Methods)
      session.extend(Webrat::Matchers)
      session.visit('http://' + ENV['CUCUMBER_HOST'] + ENV['CUCUMBER_BASE_PATH'])
      session
    end
    

    Note that if you're using Mechanize, Webrat will also fail to follow your redirects because it won't interpret the current host correctly. To work around this, you can add session.header('Host', ENV['CUCUMBER_HOST']) to the above.

    To make sure the right paths are being used everywhere for visiting and matching, add ENV['CUCUMBER_BASE_PATH'] + to the beginning of your paths_to method in paths.rb, if you use it. It should look like this:

      def path_to(page_name)
        ENV['CUCUMBER_BASE_PATH'] + 
    
        case page_name
    

    Apologies if anyone got a few e-mails from this -- I originally tried to post as a comment and Stack Overflow's irritating UI got the better of me.