Rails / Capybara-测试该表单不提交 [英] Rails/Capybara- Test that form does not submit

查看:79
本文介绍了Rails / Capybara-测试该表单不提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Rails应用程序中,我使用以下jQuery通过在输入字段中按输入来禁用提交表单的功能:

In my Rails app, I used the following jQuery to disable the ability to submit a form by pressing 'enter' in an input field:

$('input').on('keydown', function(e) {
  if(e.which == '13') {
    return false;
  }
})

我想用Capybara对此进行测试,但无法弄清楚怎么样。例如:

I wanted to test this with Capybara, but can't figure out how. For example:

# the form being tested creates a new Shift object: 
test "enter does not submit form" do
  shift_count = Shift.count
  # fill in form, etc...
  page.driver.browser.execute_script "var e = jQuery.Event('keydown'); e.which = 13; $('#shift_employee').trigger( e );"
  assert Shift.count == shift_count
end

即使jQuery函数被注释掉了,大概是因为它在ActiveRecord有时间将新记录保存到数据库之前计算 Shift.count

This test passes even when the jQuery function is commented out, presumably because it calculates Shift.count before ActiveRecord has had time to save the new the record to the database.

我还尝试让jQuery函数执行自定义的 $。get()请求,控制器以简单文本响应,认为这会建立足够的时间来完成所有服务器端工作。但这仍然行不通,我认为这是因为,无论我如何设置jQuery函数,都将在生成任何AJAX内容后始终提交表单并保存新记录。

I also tried having the jQuery function do a custom $.get() request, to which the controller responds with simple text, thinking that this would build in enough time for all server-side work to be completed. But this still doesn't work, and I think it's because, no matter how I set up the jQuery function, the submission of the form and saving of the new record will always occur after any AJAX stuff I build in.

关于如何可靠地测试未提交表单的任何想法?

Any ideas on how I can reliably test that the form was not submitted?

推荐答案

让Capybara重新访问该页面,然后检查 Shift.count ,使它起作用。现在,当注释掉jQuery函数时,该测试失败,而当该函数取消注释时,该测试通过。不过,我仍然想知道是否有更好的方法。

I got it to work by having Capybara revisit the page, and then checking Shift.count. The test now fails when the jQuery function is commented out, and passes when the function is uncommented. I'd still like to know if there's a better way, though.

这篇关于Rails / Capybara-测试该表单不提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆