Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With Capybara, how do I switch to the new window for links with "_blank" targets?

Perhaps this isn't actually the issue I'm experiencing, but it seems that when I "click_link" a link with target="_blank", the session keeps the focus on the current window.

So I either want to be able to switch to the new window, or to ignore the _blank attribute - essentially, I just want it to actually go to the page indicated by the link so I can make sure it's the right page.

I use the webkit and selenium drivers.


I submitted my findings thus far below. A more thorough answer is much appreciated.

Also, this only works with selenium - the equivalent for the webkit driver (or pointing out where I could discover it myself) would be much appreciated.

like image 715
GlyphGryph Avatar asked Sep 30 '11 14:09

GlyphGryph


3 Answers

Capybara >= 2.3 includes the new window management API. It can be used like:

new_window = window_opened_by { click_link 'Something' }
within_window new_window do
  # code
end
like image 121
Andrei Botalov Avatar answered Nov 17 '22 22:11

Andrei Botalov


This solution only works for the Selenium driver

All open windows are stores in Selenium's

response.driver.browser.window_handles

Which seems to be an array. The last item is always the window that was most recently opened, meaning you can do the following to switch to it.

Within a block:

new_window=page.driver.browser.window_handles.last 
page.within_window new_window do
  #code
end

Simply refocus for current session:

session.driver.browser.switch_to.window(page.driver.browser.window_handles.last)

Referenced on the capybara issues page: https://github.com/jnicklas/capybara/issues/173

More details on Selenium's window switching capabilities: http://qastuffs.blogspot.com/2010/10/testing-pop-up-windows-using-selenium.html

like image 54
GlyphGryph Avatar answered Nov 17 '22 20:11

GlyphGryph


This is now working with Poltergeist. Although window_handles is still not implemented (you need a window name, i.e. via a JavaScript popup):

within_window 'other_window' do
  current_url.should match /example.com/
end

Edit: Per comment below, Poltergeist now implements window_handles since version 1.4.0.

like image 11
Kridsada Thanabulpong Avatar answered Nov 17 '22 20:11

Kridsada Thanabulpong