如何使用 RSpec/RoR 测试 AJAX 请求?
我对 RoR 相当陌生,最近开始学习 BDD/Rspec 来测试我的应用程序。我一直在寻找一种规范 AJAX 请求的方法,但到目前为止我还没有找到太多关于这方面的文档。
有人知道该怎么做吗?我正在使用 Rails 2.3.8、rspec 1.3.0 和 mocha 0.9.8 作为我的存根(我也在学习过程中......)
I'm fairly new to RoR and recently started learning BDD/Rspec for testing my application. I've been looking for a way to spec an AJAX request, but so far I haven't found much documentation on this at all.
Anyone know how to do this? I'm using rails 2.3.8, rspec 1.3.0 and mocha 0.9.8 for my stubs (which I'm also in the process of learning...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您正在谈论在控制器规范内对其进行测试,通常会调用
该控制器规范来向索引操作发出 HTTP 请求,那么您将改为
使用 GET 调用以向索引操作发出 XmlHttpRequest (AJAX) 请求。
If you're talking about testing it inside your controller specs, where you normally call
to make an HTTP request to the index action, you would instead call
to make an XmlHttpRequest (AJAX) request to the index action using GET.
Rails 5 / 6
从 Rails 5.0(使用 RSpec 3.X)开始,尝试像这样设置
xhr: true
:背景
以下是 ActionController::TestCase。设置 xhr 标志最终会添加以下标头:
Rails 5 / 6
Since Rails 5.0 (with RSpec 3.X), try setting
xhr: true
like this:Background
Here's the relevant code in the ActionController::TestCase. Setting the
xhr
flag ends up adding the following headers:Rails 5 和 rspec > 的语法发生了一些变化。 3.1(我相信)
对于 POST 请求:
您现在需要为 GET 请求显式设置 params
:
对于 Rails 4 和 rspec <= 3.1
GET 请求:
Syntax changed a bit for Rails 5 and rspec > 3.1(i believe)
for POST requests:
you now need explicitely set
params
for GET requests:
for rails 4 and rspec <= 3.1
GET requests:
这是一个完整的示例:
Here is a full example: