如何使用 RSpec/RoR 测试 AJAX 请求?

发布于 2024-09-28 18:34:36 字数 176 浏览 1 评论 0原文

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

逆光下的微笑 2024-10-05 18:34:36

如果您正在谈论在控制器规范内对其进行测试,通常会调用

get :index

该控制器规范来向索引操作发出 HTTP 请求,那么您将改为

xhr :get, :index

使用 GET 调用以向索引操作发出 XmlHttpRequest (AJAX) 请求。

If you're talking about testing it inside your controller specs, where you normally call

get :index

to make an HTTP request to the index action, you would instead call

xhr :get, :index

to make an XmlHttpRequest (AJAX) request to the index action using GET.

白色秋天 2024-10-05 18:34:36

Rails 5 / 6

从 Rails 5.0(使用 RSpec 3.X)开始,尝试像这样设置 xhr: true

get :index, xhr: true

背景

以下是 ActionController::TestCase。设置 xhr 标志最终会添加以下标头:

if xhr
  @request.set_header "HTTP_X_REQUESTED_WITH", "XMLHttpRequest"
  @request.fetch_header("HTTP_ACCEPT") do |k|
    @request.set_header k, [Mime[:js], Mime[:html], Mime[:xml], "text/xml", "*/*"].join(", ")
  end
end

Rails 5 / 6

Since Rails 5.0 (with RSpec 3.X), try setting xhr: true like this:

get :index, xhr: true

Background

Here's the relevant code in the ActionController::TestCase. Setting the xhr flag ends up adding the following headers:

if xhr
  @request.set_header "HTTP_X_REQUESTED_WITH", "XMLHttpRequest"
  @request.fetch_header("HTTP_ACCEPT") do |k|
    @request.set_header k, [Mime[:js], Mime[:html], Mime[:xml], "text/xml", "*/*"].join(", ")
  end
end
触ぅ动初心 2024-10-05 18:34:36

Rails 5 和 rspec > 的语法发生了一些变化。 3.1(我相信)

对于 POST 请求:

post :create, xhr: true, params: { polls: { question: 'some' } }

您现在需要为 GET 请求显式设置 params

get :action, xhr: true, params: { id: 10 }

对于 Rails 4 和 rspec <= 3.1

xhr post :create, { polls: { question: 'some' } }

GET 请求:

xhr get :show, id: 10

Syntax changed a bit for Rails 5 and rspec > 3.1(i believe)

for POST requests:

post :create, xhr: true, params: { polls: { question: 'some' } }

you now need explicitely set params

for GET requests:

get :action, xhr: true, params: { id: 10 }

for rails 4 and rspec <= 3.1

xhr post :create, { polls: { question: 'some' } }

GET requests:

xhr get :show, id: 10
束缚m 2024-10-05 18:34:36

这是一个完整的示例:

get "/events", xhr: true, params: { direction: "past" }

Here is a full example:

get "/events", xhr: true, params: { direction: "past" }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文