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

后端 未结 15 1856
花落未央
花落未央 2020-12-02 09:54

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 w

相关标签:
15条回答
  • 2020-12-02 10:11

    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
    
    0 讨论(0)
  • 2020-12-02 10:13

    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

    0 讨论(0)
  • 2020-12-02 10:15

    You can pass a name, url or title of the window also (But now its dipricated)

      let(:product) { create :product }
    
      it 'tests' do
        visit products_path
        click_link(product.id)
    
        within_window(product_path(product)) do
          expect(page).to have_content(product.title)
        end
      end
    

    You can pass a labda or a proc also

    within_window(->{ page.title == 'Page title' }) do
      click_button 'Submit'
    end
    

    wish it stretches the method usage to more clearly understaing

    0 讨论(0)
  • 2020-12-02 10:22

    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
    
    0 讨论(0)
  • 2020-12-02 10:22

    The main implementation (window_opened_by) raises an error for me:

    *** Capybara::WindowError Exception: block passed to #window_opened_by opened 0 windows instead of 1
    

    So, I resolve it by this solution:

    new_window = open_new_window
    
    within_window new_window do
      visit(click_link 'Something')
    end
    
    page.driver.browser.window_handles
    # => ["CDwindow-F7EF6D3C12B68D6B6A3DFC69C2790718", "CDwindow-9A026DEC65C3C031AF7D2BA12F28ADC7"]
    
    0 讨论(0)
  • 2020-12-02 10:23

    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)

    0 讨论(0)
提交回复
热议问题