Richlewis
Richlewis

Reputation: 15384

Can't access new window in Capybara

I've been trying to access a new window (well tab) when using Capybara, but keep getting

Selenium::WebDriver::Error::NoSuchWindowError: no such window

My process and understanding so far is

@session_1 = Capybara::Session.new(:chrome)
@session_1.visit("www.google.com")

So at this stage i have google open. Now lets say i want to open google in a new tab/window

@session_1.open_new_window

This opens a new window, and to access those windows I can do

@session_1.windows

which returns an array of windows

[#<Window @handle="CDwindow-09B6E81E-7874-4686-86A9-8BFB917E0F4F">,
#<Window @handle="CDwindow-5DA14173-8D63-422A-BF98-39B7C2A5D2DB">]

So as a test I wanted to check that latest windows url matches about:blank

@new_tab = @session_1.windows.last
# @new_tab = #<Window @handle="CDwindow-5DA14173-8D63-422A-BF98-39B7C2A5D2DB">

page.within_window @new_tab do 
  expect(current_url).to eq('about:blank')
end

It's here I get the error.

What I would like to know is

1) How to select the new tab

2) how to open a new url within the new tab

Upvotes: 0

Views: 1208

Answers (2)

Thomas Walpole
Thomas Walpole

Reputation: 49950

Capybara has a number of methods for dealing with windows, and open_new_window returns the window it opened so there's no need to go looking through the list of all windows

@session1.within_window(@session_1.open_new_window) do
  @sessuion1.visit("url")
  ... more actions performed in the new window
end

Upvotes: 1

Richlewis
Richlewis

Reputation: 15384

So I found the answer, turns out it was a lot simpler than i was trying, credit goes to Keiran Betteley and this post

@session_1.open_new_window
@session_1.switch_to_window(@session_1.windows.last)
@session_1.visit("url")

Upvotes: 2

Related Questions