如何使用Capybara模拟鼠标悬停

时间:2012-03-20 09:23:25

标签: ruby-on-rails rspec capybara

基本上,我要做的是点击一个按钮,当悬停在另一个元素(其父元素)上时,该按钮变为可见。

我尝试在隐藏按钮的父级上使用trigger.('mouseover'),但这似乎不起作用。

以下是规范中的代码段:

 # 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")

错误......

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

我想知道如何在页面上显示.actions按钮,以便之后点击它。

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:96)

Capybara从版本2.1提供Element#hover method

find('.some_class').hover

此方法在Capybara::Selenium::Driver中的实现方式与@ AlexD的答案几乎相同。

请注意,在Selenium it's usually better to turn native events on中使用#hover

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

答案 1 :(得分:18)

Alex在他的博客中描述了这些问题的解决方案:查看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)

答案 2 :(得分:7)

我找到了一种使用Capybara + Selenium驱动程序来模拟“鼠标悬停”的方法:

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

答案 3 :(得分:4)

使用Capybara + Selenium可以在此命令中使用“hover”:

page.driver.browser.action.move_to(page.find('YourElement').native).perform
相关问题