Andrew
Andrew

Reputation: 238937

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?

Upvotes: 1

Views: 1391

Answers (2)

Michael
Michael

Reputation: 548

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.

Upvotes: 3

mightilybix
mightilybix

Reputation: 489

For Mechanize, the first URL you specify will be considered the base URL. For example:

require "rubygems"
require "mechanize"

agent = Mechanize.new
agent.get("http://some-site.org")

# Subsequent requests can now use the relative path:

agent.get("/contact.html")

This way you only specify the base URL once.

Upvotes: 1

Related Questions