How to emulate mouse hover with Capybara

Ruby on-RailsRspecCapybara

Ruby on-Rails Problem Overview


Basically, what I'm trying to do is click on a button that becomes visible when hovering another element (its parent).

I have tried to use trigger.('mouseover') on the parent of the hidden button, but that doesn't seem to work.

Here's a code snippet from the spec:

 # label[for ... ] -> the parent element
 page.execute_script("$('label[for=\"department_#{department.id}\"]').trigger(\"mouseover\")")     
 # le hidden button
 find(".actions").click     
 # some <li> on a list that drops down when clicking the hidden button    
 click_on("Edit department")
  

And the error ...

 Failure/Error: click_on("Edit department")
 Selenium::WebDriver::Error::ElementNotVisibleError:
 Element is not currently visible and so may not be interacted with

I would like to know how can I make the .actions button visible on the page, in order to click it afterwards.

Any help would be much appreciated.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Capybara provides Element#hover method from version 2.1:

find('.some_class').hover

This method is implemented in Capybara::Selenium::Driver in almost the same way as in @AlexD's answer.

Note that to use #hover in Selenium it's usually better to turn native events on:

Capybara.register_driver :selenium do |app|
  profile = Selenium::WebDriver::Firefox::Profile.new
  profile.native_events = true
  Capybara::Selenium::Driver.new(app, :browser => :firefox, profile: profile)
end

Solution 2 - Ruby on-Rails

Alex described the solution of such problems in his blog: check it out http://aokolish.me/blog/2012/01/22/testing-hover-events-with-capybara

RSpec.configure do |config|
  # ...
  Capybara.javascript_driver = :webkit
end

page.find('#element').trigger(:mouseover)

Solution 3 - Ruby on-Rails

I found a way to simulate "mouse hover" using Capybara + the Selenium driver:

module Capybara
  module Node
    class Element
      def hover
        @session.driver.browser.action.move_to(self.native).perform
      end
    end
  end
end

Solution 4 - Ruby on-Rails

Using Capybara + Selenium it is possible to use "hover" with this command:

page.driver.browser.action.move_to(page.find('YourElement').native).perform

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionadritha84View Question on Stackoverflow
Solution 1 - Ruby on-RailsAndrei BotalovView Answer on Stackoverflow
Solution 2 - Ruby on-RailsSaid KaldybaevView Answer on Stackoverflow
Solution 3 - Ruby on-RailsAlex DView Answer on Stackoverflow
Solution 4 - Ruby on-RailstuhajView Answer on Stackoverflow