Ruby-on-rails 如何用 Capybara 模拟鼠标悬停
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9784118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to emulate mouse hover with Capybara
提问by adritha84
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.
我试图trigger.('mouseover')在隐藏按钮的父级上使用,但这似乎不起作用。
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 .actionsbutton visible on the page, in order to click it afterwards.
我想知道如何使.actions按钮在页面上可见,以便之后单击它。
Any help would be much appreciated.
任何帮助将非常感激。
回答by Andrei Botalov
Capybara provides Element#hovermethodfrom version 2.1:
Capybara 提供了2.1 版本的Element#hover方法:
find('.some_class').hover
This method is implemented in Capybara::Selenium::Driverin almost the same way as in @AlexD's answer.
此方法的实现Capybara::Selenium::Driver方式与@AlexD 的答案几乎相同。
Note that to use #hoverin Selenium it's usually better to turn native events on:
请注意,要#hover在 Selenium 中使用,通常最好打开本机事件:
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
回答by Said Kaldybaev
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
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)
回答by Alex D
I found a way to simulate "mouse hover" using Capybara + the Selenium driver:
我找到了一种使用 Capybara + Selenium 驱动程序模拟“鼠标悬停”的方法:
module Capybara
module Node
class Element
def hover
@session.driver.browser.action.move_to(self.native).perform
end
end
end
end
回答by tuhaj
Using Capybara + Selenium it is possible to use "hover" with this command:
使用 Capybara + Selenium 可以通过以下命令使用“悬停”:
page.driver.browser.action.move_to(page.find('YourElement').native).perform

