在Rails中,您如何对Javascript响应格式进行功能测试?

问题描述 投票:33回答:9

如果您的控制器操作如下所示:

respond_to do |format|
  format.html { raise 'Unsupported' }
  format.js # index.js.erb
end

你的功能测试看起来像这样:

test "javascript response..." do
  get :index
end

它将执行respond_to块的HTML分支。

如果你试试这个:

test "javascript response..." do
  get 'index.js'
end

它执行视图(index.js.erb)而没有运行控制器动作!

javascript ruby-on-rails response functional-testing
9个回答
59
投票

用你的普通参数传递:format以触发该格式的响应。

get :index, :format => 'js'

无需弄乱您的请求标头。


25
投票

与rspec:

it "should render js" do
  xhr :get, 'index'
  response.content_type.should == Mime::JS
end

并在您的控制器操作中:

respond_to do |format|
  format.js
end

5
投票

将接受的内容类型设置为您想要的类型:

@request.accept = "text/javascript"

将此与您的get :index测试相结合,它将对控制器进行适当的调用。


3
投票

在请求之前使用此:

@request.env['HTTP_ACCEPT'] = 'text/javascript'

1
投票

这三个似乎是等价的:

  1. get :index, :format => 'js'
  2. @request.env['HTTP_ACCEPT'] = 'text/javascript'
  3. @request.accept = "text/javascript"

它们使控制器使用js模板(例如index.js.erb)

模拟XHR请求(例如获取HTML片段),您可以使用:@request.env['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"

这意味着request.xhr?将返回真实。

请注意,在模拟XHR时,我必须指定预期的格式,否则我会收到错误:

get :index, format: "html"

在Rails 3.0.3上测试过。

我从Rails源代码获得后者,这里:https://github.com/rails/rails/blob/6c8982fa137421eebdc55560d5ebd52703b65c65/actionpack/lib/action_dispatch/http/request.rb#L160


1
投票

RSpec 3.7和Rails 5.x解决方案:

其中一些答案在我的案例中有点过时,所以我决定为那些运行Rails 5和RSpec 3.7的人提供答案:

it "should render js" do
  get :index, xhr: true

  expect(response.content_type).to eq('text/javascript')
end

与史蒂夫的answer非常相似,只有一些调整。第一个是xhr作为布尔键/对传递。其次是我现在使用expect,因为如果使用should接收弃用警告。比较响应的content_type等于text/javascript为我工作。


0
投票

使用这样的代码作为参数和用户ID等,请注意format选项与id和nested_attributes等其他参数的哈希值相同。

put :update, {id: record.id, nested_attributes: {id: 1, name: "John"}, format: :js}, user.id

0
投票

上述许多答案都已过时。

在RSpec 3+中执行此操作的正确方法是post some_path, xhr: true

当试图使用xhr :post, "some_path"时,直接来自RSpec本身的弃用警告:

DEPRECATION WARNING: `xhr` and `xml_http_request` are deprecated and will be removed in Rails 5.1.
Switch to e.g. `post comments_path, params: { comment: { body: 'Honey bunny' } }, xhr: true`.

此外,xhr :post, "some_path"导致一些时髦的错误,post some_path, xhr: true不会发生。


0
投票

我有类似的问题:

# controller
def create
  respond_to do |format|
    format.js
  end
end

# test

test "call format js" do
  record = promos(:one)
  post some_url(record)
  assert true
end

结果如下:

> rails test
Error:
ActionController::UnknownFormat: ActionController::UnknownFormat

我修改了它,调整到测试(添加标题):

test "call format js" do
  record = promos(:one)
  headers = { "accept" => "text/javascript" }
  post some_url(record), headers: headers
  assert true
end

卷轴(i.0.0.bat)

© www.soinside.com 2019 - 2024. All rights reserved.