Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto scroll a button into view with Capybara and Selenium

Sometime last month (June 2013), several of our Capybara tests started failing mainly because the buttons they are trying to click are not in view. Ideally, I'd like to figure out what changed. We're currently on selenium-webdriver 2.33 but I've tried going back to 2.29 and it still doesn't work. We're running against Firefox only at the moment and maybe it's due to a newer version of Firefox.

Barring that, I can't figure out how to scroll the buttons into view. From what I gather, I can use scrollIntoView but not sure how to call it in the Capybara step. I tried variations on:

 Capybara.current_session.driver.execute_script("arguments[0].scrollIntoView(true;)", find_button(button).native)

But with no luck because find_button itself doesn't work.

Note: we are selecting based on the button's text. Selecting based on ID is possible but will require a lot of changes to our UI tests so we'd like to avoid it.

like image 669
Kyle Baley Avatar asked Jul 12 '13 19:07

Kyle Baley


People also ask

Does scrollIntoView work horizontally?

((JavascriptExecutor) driver). executeScript("arguments[0]. scrollIntoView(true);", element); This works for vertical scrolling but not for horizontal.

How do I get the element in view 1 pick option?

Say your page displays a list of names and you want a certain person to be highlighted and scrolled into view. There's a browser API for that: Element. scrollIntoView() , which scrolls an element into view.


1 Answers

I normally have a module JavascriptDriver that I use to include Selenium functionality in a test, and there I define a helper method:

module JavascriptDriver
  # other code that prepares capybara to work with selenium

  def scroll_to(element)
    script = <<-JS
      arguments[0].scrollIntoView(true);
    JS

    Capybara.current_session.driver.browser.execute_script(script, element.native)
  end
end

And then in your test you can utilize that code by passing a normal Capybara element:

scroll_to(page.find("button.some-class", visible: false))
like image 146
Gray Kemmey Avatar answered Sep 28 '22 23:09

Gray Kemmey