2012-03-20 33 views
42

基本上,我想要做的是點擊一個按鈕,變得可見時,懸停其他元素(其父母)。如何模仿鼠標懸停與水豚

我試圖在隱藏按鈕的父級上使用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按鈕在網頁上顯示,在以後點擊它。

任何幫助將不勝感激。

回答

81

水豚提供版本2.1的Element#hover method

find('.some_class').hover 

這個方法在Capybara::Selenium::Driver中以@ AlexD的回答幾乎相同的方式實現。

注意,在硒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 
+0

爲什麼這不是最好的答案? – manu 2014-07-04 11:25:49

+0

OP(原始海報)一年前得到了答案,並接受了它。時間已經過去了,現在這個答案更好了,但是OP需要選擇它才能將它移到頂端。 – 2014-07-10 13:53:35

+0

這不適用於'xvfb-run -a' :( – brauliobo 2015-08-30 23:59:37

18

亞歷克斯描述了在他的博客中這樣的問題的解決:檢查出來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) 
+0

'mouseenter'解決我的問題最終 – adritha84 2012-03-20 12:49:03

+3

我如何克服'水豚:: NotSupportedByDriverError'錯誤? – Hengjie 2013-03-13 10:19:59

+3

@恆傑'page.execute_script('$(「#element」)。trigger(「mouseenter」)')' – Andrew 2013-03-25 05:35:04

7

我找到了一種方法來模擬「鼠標懸停」使用水豚+硒司機:

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

你把這個文件放在哪裏? – Hengjie 2013-03-13 10:19:43

+1

如果你有一個共同的'spec_helper.rb'或'test_helper.rb'或類似的文件,你可以把它放在那裏。 – 2013-03-14 08:20:40

4

使用水豚+硒,可以使用 「懸停」 使用下面的命令:

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