In Rails, how do you functional test a Javascript response format?

前端 未结 9 930
攒了一身酷
攒了一身酷 2021-01-31 15:41

If your controller action looks like this:

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

and yo

9条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 16:39

    These three seem to be equivalent:

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

    They cause the controller to use a js template (e.g. index.js.erb)

    Whereas simulating an XHR request (e.g. to get a HTML snippet) you can use this: @request.env['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"

    This means request.xhr? will return true.

    Note that, when simulating XHR, I had to specify the expected format or I got an error:

    get :index, format: "html"

    Tested on Rails 3.0.3.

    I got the latter from the Rails source, here: https://github.com/rails/rails/blob/6c8982fa137421eebdc55560d5ebd52703b65c65/actionpack/lib/action_dispatch/http/request.rb#L160

提交回复
热议问题