With Capybara, how do I switch to the new window f

2019-01-13 00:49发布

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.

13条回答
老娘就宠你
2楼-- · 2019-01-13 00:51

As of May 2014 the following code works on capybara-webkit

 within_window(page.driver.browser.window_handles.last) do
   expect(current_url).to eq('http://www.example.com/')
 end
查看更多
【Aperson】
3楼-- · 2019-01-13 00:52

To explicitly change window, you use switch_to_window

  def terms_of_use
    terms_window = window_opened_by do
      click_link(@terms_link)
    end
    switch_to_window(terms_window)
  end

An after that method browser will work in the new page, instead of wrap everything in a within_window block

查看更多
小情绪 Triste *
4楼-- · 2019-01-13 00:53

Capybara provides some methods to ease finding and switching windows:

facebook_window = window_opened_by do
  click_button 'Like'
end
within_window facebook_window do
  find('#login_email').set('a@example.com')
  find('#login_password').set('qwerty')
  click_button 'Submit'
end

More details here: Capybara documentation

查看更多
劫难
5楼-- · 2019-01-13 00:53

I know this is old post, but for what its worth in capybara 2.4.4

within_window(switch_to_window(windows.last)) do 
    # in my case assert redirected url from a prior click action
    expect(current_url).to eq(redirect['url'])
end
查看更多
别忘想泡老子
6楼-- · 2019-01-13 00:53

The best idea is to update capybara to the latests version (2.4.1) and just use windows.last because page.driver.browser.window_handles is deprecated.

查看更多
我想做一个坏孩纸
7楼-- · 2019-01-13 00:55

This works for me in capybara-webkit:

within_window(windows.last) do
  # code here
end

(I'm using capybara 2.4.1 and capybara-webkit 1.3.0)

查看更多
登录 后发表回答