How to get the full URL with the current path in Capybara
Asked Answered
M

4

35

I'm new to writing tests in capybara and I'm having trouble getting the current URL of a page. I wrote it like this:

url = page.current_url + page.current_path

Somehow its just returning the base URL. Help is much appreciated.

Markley answered 11/12, 2013 at 14:56 Comment(0)
I
39

Try this:

url = URI.parse(current_url)
Ive answered 11/12, 2013 at 14:59 Comment(2)
url = URI.parse(current_url).to_sKreindler
current_url gives the exact same response as the line above ^^Lindbom
M
17

from capybara session doc:
Fully qualified URL of the current page

def current_url
  driver.current_url
end

Path of the current page, without any domain information

def current_path
  URI.parse(current_url).path
end

I think that what you are doing is not right

Microgram answered 11/12, 2013 at 15:2 Comment(2)
Yeah, I was doing it all wrong. But I will use what you provided in my future work. Thanks.Markley
@Philidor , am new to RSpec. where we need to define this function? in normal code file or spec file which we create in the spec folder?Thaumaturge
E
7

you could use have_current_path:

expect(page).to have_current_path(new_user_path)

before seeing that I was doing something like:

  def current_path
    current_uri = URI.parse(page.current_url)
    current_path = current_uri.path
    current_path += "?#{current_uri.query}" if current_uri.query.present?
    current_path
  end
Eldred answered 27/4, 2019 at 17:15 Comment(0)
S
0

You can use the has_current_path matcher and match for full URLs.

expect(page).to have_current_path('https://example.com', url: true)

Have a look at the Capybara test suite for more examples: has_current_path_spec.rb#L54.

Suntan answered 5/3, 2024 at 13:20 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.