Skip to content

Commit

Permalink
Issue-2544 rack test base element support
Browse files Browse the repository at this point in the history
  • Loading branch information
twalpole committed Apr 30, 2022
1 parent 614274b commit ec5a50f
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 4 deletions.
37 changes: 33 additions & 4 deletions lib/capybara/rack_test/browser.rb
Expand Up @@ -73,14 +73,18 @@ def process(method, path, attributes = {}, env = {})
end

def build_uri(path)
URI.parse(path).tap do |uri|
uri.path = request_path if path.empty? || path.start_with?('?')
uri.path = '/' if uri.path.empty?
uri.path = request_path.sub(%r{/[^/]*$}, '/') + uri.path unless uri.path.start_with?('/')
uri = URI.parse(path)
base_uri = base_relative_uri_for(uri)

uri.path = base_uri.path + uri.path unless uri.absolute? || uri.path.start_with?('/')

if base_uri.absolute?
base_uri.merge(uri)
else
uri.scheme ||= @current_scheme
uri.host ||= @current_host
uri.port ||= @current_port unless uri.default_port == @current_port
uri
end
end

Expand Down Expand Up @@ -125,6 +129,25 @@ def title

protected

def base_href
find(:css, 'head > base').first&.[](:href).to_s
end

def base_relative_uri_for(uri)
base_uri = URI.parse(base_href)
current_uri = URI.parse(safe_last_request&.url.to_s).tap do |c|
c.path.sub!(%r{/[^/]*$}, '/') unless uri.path.empty?
c.path = '/' if c.path.empty?
end

if [current_uri, base_uri].any?(&:absolute?)
current_uri.merge(base_uri)
else
base_uri.path = current_uri.path if base_uri.path.empty?
base_uri
end
end

def build_rack_mock_session
reset_host! unless current_host
Rack::MockSession.new(app, current_host)
Expand All @@ -136,6 +159,12 @@ def request_path
'/'
end

def safe_last_request
last_request
rescue Rack::Test::Error
nil
end

private

def fragment_or_script?(path)
Expand Down
14 changes: 14 additions & 0 deletions lib/capybara/spec/session/visit_spec.rb
Expand Up @@ -201,4 +201,18 @@
@session.visit('/get_cookie')
expect(@session).to have_content('root cookie')
end

context 'with base element' do
it 'should use base href with relative links' do
@session.visit('/base/with_base')
@session.click_link('Title page')
expect(@session).to have_current_path('/with_title')
end

it 'should use base href with bare queries' do
@session.visit('/base/with_base')
@session.click_link('Bare query')
expect(@session).to have_current_path('/?a=3')
end
end
end
16 changes: 16 additions & 0 deletions lib/capybara/spec/test_app.rb
Expand Up @@ -177,6 +177,22 @@ def initialize(string1, msg)
HTML
end

get '/base/with_base' do
<<-HTML
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>Origin</title>
</head>
<body>
<a href="with_title">Title page</a>
<a href="?a=3">Bare query</a>
</body>
</html>
HTML
end

get '/download.csv' do
content_type 'text/csv'
'This, is, comma, separated' \
Expand Down

0 comments on commit ec5a50f

Please sign in to comment.