开发者

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

I would 开发者_JS百科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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜