56

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.

adritha84
  • 957
  • 1
  • 7
  • 15

4 Answers4

122

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
Andrei Botalov
  • 20,686
  • 11
  • 89
  • 123
  • Why is this not the top answer? – manu Jul 04 '14 at 11:25
  • OP (Original poster) got his answer a year earlier and accepted it. Time has moved on, and this answer is now better, but OP needs to select it to move it to the top. – Affable Geek Jul 10 '14 at 13:53
  • Confirmed that find('.some_class').hover works. Then for my case, it allowed me to click a link that was only visible on hover by placing that code afterwards. I didn't have to drop down to native events (I also like to switch between Selenium and Capybara Webkit to either see whats happening or for speed) – Greg Blass Mar 22 '16 at 20:41
19

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)
Said Kaldybaev
  • 9,380
  • 8
  • 36
  • 53
7

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
Alex D
  • 29,755
  • 7
  • 80
  • 126
5

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

page.driver.browser.action.move_to(page.find('YourElement').native).perform
tuhaj
  • 527
  • 7
  • 9