Ruby-on-rails 如何使用 RSpec/RoR 测试 AJAX 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3971268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:25:45  来源:igfitidea点击:

How do you test an AJAX request with RSpec/RoR?

ruby-on-railsajaxtestingrspecmocha

提问by user480826

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.

我对 RoR 还很陌生,最近开始学习 BDD/Rspec 来测试我的应用程序。我一直在寻找一种规范 AJAX 请求的方法,但到目前为止我还没有找到太多关于此的文档。

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...)

有人知道怎么做吗?我正在使用 rails 2.3.8、rspec 1.3.0 和 mocha 0.9.8 作为我的存根(我也在学习......)

回答by Robert Speicher

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

要向索引操作发出 HTTP 请求,您可以调用

xhr :get, :index

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

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

回答by odlp

Rails 5 / 6

导轨 5 / 6

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

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

get :index, xhr: true

Background

背景

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

这是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

回答by user1136228

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

Rails 5 和 rspec > 3.1 的语法略有变化(我相信)

for POST requests:

对于 POST 请求:

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

you now need explicitely set params

你现在需要明确设置 params

for GET requests:

对于 GET 请求:

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

for rails 4 and rspec <= 3.1

对于 rails 4 和 rspec <= 3.1

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

GET requests:

获取请求:

xhr get :show, id: 10