黄瓜,水豚和selenium – 提交没有按钮的表格

我有一个使用Cucumber,capybara和selenium驱动器的测试。 此测试应该转到表单并提交。 正常的文字是

Scenario: Fill form Given I am on the Form page When I fill in "field1" with "value1" And I fill in "field2" with "value2" And I press "OK" Then I should see "Form submited" 

问题是我没有表单中的OK按钮,我需要一种方法来执行“form.submit”,而不需要单击任何按钮或链接 – 就像在表单字段中按Enter时一样使用浏览器。

我不知道如何告诉capybara提交表格。 我该怎么做?

您可以访问selenium send_keys方法来调用返回事件,例如

  find_field('field2').native.send_key(:enter) 

简单的解决方案:

 When /^I submit the form$/ do page.evaluate_script("document.forms[0].submit()") end 

为capybara-envjs工作。 也应该与selenium一起使用。

我必须自己解决这个问题。 在webrat我有这样的事情:

 Then /^I submit the "([^\"]*)" form$/ do |form_id| submit_form form_id end 

我在Capybara能够实现同样的目标:

  Then /^I submit the "([^\"]*)" form$/ do |form_id| element = find_by_id(form_id) Capybara::RackTest::Form.new(page.driver, element.native).submit :name => nil end 

使用Capybara Selenium驱动程序,您可以执行以下操作:

 within(:xpath, "//form[@id='the_form']") do locate(:xpath, "//input[@name='the_input']").set(value) locate(:xpath, "//input[@name='the_input']").node.send_keys(:return) end 

简单地说:你不能。

有些浏览器根本不允许您提交没有提交按钮的表单(最明显的是Internet Explorer <= 6)。 所以这种形式从一开始就是一个坏主意。 添加一个提交按钮并使用CSS将其放在屏幕上。

您可能可以自己动手(例如,我提交带有“Ok”链接的表单),并自己模拟提交function。

这里是在Rails 3中删除的javascript模拟,以支持“不引人注目”(强调引号)Javascript。 这条线

 Capybara::Driver::RackTest::Form.new(driver, js_form(self[:href], emulated_method)).submit(self) 

可能是回答你问题的线索。 完整的代码在这里

我建议你添加一个提交按钮,然后用CSS隐藏它。 然后,您可以测试表单提交,但仍然可以获得所需的用户行为。

使用Webrat,您可以:

 When /^I submit the form$/ do submit_form "form_id" end 

页。 307,RSpec书

显示:无解决方案不适用于使用selenium驱动程序的水豚,因为selenium抱怨与不可见元素交互。 如果您尝试上述解决方案,您可能会看到以下错误消息:

 Element is not currently visible and so may not be interacted with (Selenium::WebDriver::Error::ElementNotVisibleError) 

您可以尝试发送换行符:

 find_field('field2').native.send_key("\n") 

这有点像hackish,但它满足了需求。 我修补了#submit以支持元素上的#submit方法。

它不健壮,因为它从每个输入元素的namevalue属性中天真地创建POST参数。 (在我的例子中,我的所有元素都是hidden类型的,所以它工作正常)。

 class Capybara::Node::Element # If self is a form element, submit the form by building a # parameters from all 'input' tags within this form. def submit raise "Can only submit form, not #{tag_name}" unless tag_name =~ /form/i method = self['method'].to_sym url = self['action'] params = all(:css, 'input').reduce({}) do |acc, input| acc.store(input['name'], input['value']) acc end session.driver.submit(method, url, params) end end ... form = find('#my_form_with_no_submit_button') form.submit 

试试这个..

 find(:css, "input[name$='login']").native.send_keys :enter