使用Capybara webkit时未找到元素错误,但测试在非无头模式下运行良好

时间:2013-01-02 05:46:12

标签: testing capybara capybara-webkit

我正在尝试使用Capybara-webkit在无头模式下运行简单的Google搜索测试。

我已将驱动程序设置为env.rb文件:

Capybara.default_driver = :webkit
Capybara.current_driver = :webkit
Capybara.javascript_driver = :webkit

功能文件有一个简单的场景大纲,用于搜索输入并验证结果是否包含预期的输出:

    Given User opens the google page
    When she searches for "<input>"
    Then verify that the result has "<output>"

    Examples:
    |input                    | output           |
    |Agile Samurai author name|Jonathan Rasmusson|
    |Eloquent Ruby author name|Russ Olsen        |

在步骤定义中,访问Google页面并将输入输入文本框并单击搜索按钮。

Given /^User opens the google page$/ do
  visit "http://google.com"
end

When /^she searches for "(.*?)"$/ do |search_query|
        fill_in "gbqfq", :with => search_query
        click_button "gbqfba"
end

Then /^verify that the result has "(.*?)"$/ do |output|
        should have_content output
end

当我运行这些测试时,我收到错误:

  

无法找到字段“gbqfq”(Capybara :: ElementNotFound)

但是,如果我将驱动程序更改为selenium:

Capybara.default_driver = :selenium
Capybara.current_driver = :selenium
Capybara.javascript_driver = :selenium

然后,测试运行并且所有步骤都通过。

在无头模式中,是否以其他方式找到了元素? 我的方法有误吗?我无法理解为什么在无头模式下找不到元素,因为它在浏览器模式下工作正常(打开firefox实例)。

我是这个领域的新手,所以任何帮助都将深表感谢。 提前谢谢。

2 个答案:

答案 0 :(得分:2)

我使用puts page.html打印出源代码。我发现无头模式的源代码不同。

这是浏览器模式下文本框源代码的一部分:

<input id="gbqfq" class="gbqfif" type="text" value="" autocomplete="off" name="q">

这是无头模式下文本框源代码的一部分:

<input class="lst" spellcheck="false" dir="ltr" title="Google Search" value="">

由于无头模式源代码中不存在id,因此测试失败。 如果在两种模式中都有一些共同的名称,请将其用于测试。

我不确定为什么会这样。但谷歌可能会根据头部或无头模式加载不同的页面。

我尝试过像flipkart.com这样的其他网站,它们都适用于这两种模式。即两种模式中的id等都是相同的。

因此,问题中的代码没有任何问题。只需要使用两种模式中都存在的id。

答案 1 :(得分:0)

您的click_button行似乎有错误的id按钮。

应该是:

click_button "gbqfba"

所以你的线路变成了:

fill_in "gbqfq", :with => search_query
click_button "gbqfba"

我不确定这是否会有所帮助,但值得一试。

相关问题