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

后端 未结 15 1988
花落未央
花落未央 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:06

    I personally like the following approach since it works correctly regardless of JS being enabled or not.

    My Spec:

      it "shows as expected" do
        visit my_path
    
        # ...test my non-JS stuff in the current tab
    
        switch_to_new_tab
    
        # ...test my non-JS stuff in the new tab
        
        # ...keep switching to new tabs as much as necessary
      end 
    
      # OR
    
      it "shows as expected", js: true do
        visit my_path
    
        # ...test my non-JS stuff in the current tab
        # ...also test my JS stuff in the current tab
    
        switch_to_new_tab
    
        # ...test my non-JS stuff in the new tab
        # ...also test my JS stuff in the new tab
    
        # ...keep switching to new tabs as much as necessary
      end 
    
    

    Test helpers:

      def switch_to_new_tab
        current_browser = page.driver.browser
    
        if js_enabled?
          current_browser.switch_to.window(current_browser.window_handles.last)
        else
          visit current_browser.last_request.fullpath
        end
      end
    
      def js_enabled?
        Capybara.current_driver == Capybara.javascript_driver
      end
    

提交回复
热议问题