문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top