Opening a new tab in Capybara / Poltergeist
Asked Answered
V

3

6

I'm trying to open a link by clicking on it using capybara/poltergeist which opens up in a new tab.

I can't seem to get it working.

@session.find(<link>).click

just seems to stay on the same page, as does

click_link "<link>"

@session.driver.window_handles 

Only seems to give me 1 window whatever I'm doing.

How do I get that link to open in a new tab?

Seems to be a fair amount of confusion as to what works or doesn't a la (With Capybara, how do I switch to the new window for links with "_blank" targets?).

Hoping somebody has worked it out... Can't seem to get my head around it.

Ok. By updating to the latest version of poltergeist (1.6.0) we have some progress.

Now however I have two windows but no idea how to switch between them.

@session.windows

gives me

[Window @handle="0", Window @handle="1"] (slightly modified as it was going a bit funny).

But

@session.switch_to_window(1)

results in

NoMethodError: undefined method `handle' for "1":String
Vanscoy answered 9/2, 2015 at 17:46 Comment(0)
V
6

Right, as of Feb 5th 2014 and v1.6 of poltergeist, you can do this, as ...

@session.click_on "link_with_target _blank"

@session.switch_to_window(@session.windows.last)
#Do whatever you're doing
@session.current_window.close
@session.switch_to_window(@session.windows.first)

Hope that clears things up for somebody...

Vanscoy answered 10/2, 2015 at 0:56 Comment(1)
This is correct. switch_to_window wants a Window object as argument, not an index. That's why e.g. windows.last works. You can also do @session.switch_to_window(@session.windows[1]). You should accept your answer as correct!Organzine
E
5

This is what worked for me using Capybara 3.33:

new_window = window_opened_by do
  click_link 'Go to external page'
end

within_window new_window do
  assert_current_path 'http://external-page.com/?q=lala'
end 
Extensile answered 9/12, 2020 at 11:56 Comment(1)
Still works in 2024!Hepatic
M
3

I did this with

page.switch_to_window(page.windows[0])

Maybe that's useful to someone.

Mayce answered 15/6, 2017 at 10:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.