使用无头铬在rails中进行测试时的ElementNotVisibleError

时间:2018-06-14 10:59:53

标签: ruby-on-rails selenium testing capybara google-chrome-headless

我使用capybara / headless_chrome测试以下假设And I click on the text "2018/2019" within ".year"并不断得到错误

element not visible
    (Session info: headless chrome=67.0.3396.87)
    (Driver info: chromedriver=2.40.565386 (45a059dc425e08165f9a10324bd1380cc13ca363),platform=Mac OS X 10.13.5 x86_64) (Selenium::WebDriver::Error::ElementNotVisibleError)

我已经尝试按照建议here调整窗口大小。但它没有用。 我的步骤定义:

When(/^(?:|I )click on the text "([^"]*)"(?: within "([^"]*)")?$/) do |link, selector|
  begin
    page.find(:css, selector).click
  end
end

元素实际上是可见的,由Capybara找到

enter image description here

[1] pry(#<Cucumber::Rails::World>)> page.find(:css, ".year")
    => #<Capybara::Node::Element tag="a" path="/html/body/div[2]/div[2]/section/div[2]/div/div[1]/div[1]/div[2]/div/div[2]/ul/li/a">

但点击失败

[2] pry(#<Cucumber::Rails::World>)> page.find(:css, ".year").click
    Selenium::WebDriver::Error::ElementNotVisibleError: element not visible

为什么click在这里工作?

编辑: 链接的HAML是

           %ul.facet_values
            - unselected.each do |facet_value|
              %li.filtered{data: {hayf: {text: facet_value.name.downcase}}}
                = link_to facet_value.path, title: facet_value.name, class: 'year' do
                  =truncate("#{facet_value.name}", length: 24)
                - if facet.has_counts?
                  %span.small="(#{facet_value.count})"

我尝试使用Poltergeist进行无头测试并得到Poltergeist detected another element with CSS selector 'html body header div.container-fluid' at this position,并使用.trigger('click')解决了测试并通过了测试。

1 个答案:

答案 0 :(得分:0)

由于这在非无头Chrome或Poltergeist中不起作用,因此最简单的答案是该元素实际上不可见。首先删除Capybara.ignore_hidden_elements = false设置,因为在测试应用程序时没有任何意义,并且会搞砸各种等待行为。其次,在尝试点击链接之前,使用save_and_open_screenshot来了解网页的实际情况。

我猜你会发现该链接实际上并未显示,并且您的测试缺少用户必须执行的步骤才能使链接可见,是否在一个菜单,你必须首先悬停在不同的元素上?它是否在弹出窗口中你必须首先点击其他内容?是否需要滚动到?等

最后,如果您通过Selenium坚持使用Chrome,您通常会遇到的问题更少。恶作剧使用PhantomJS,它在相当长的一段时间内没有更新,也不支持现代的JS或CSS,这可能导致各种各样的陌生感。