How to configure and test external JS requests now that Rails 5.1 deprecates `xhr` and `xml_http_request`?

Viewed 158

I am testing a controller action that responds to a script that can be embedded on external sites.

xhr :get, :index, params: { format: :js }

Rails has started raising the following note

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

If I modify the controller spec as per these suggestions

get :index, params: { format: :js }, xhr: true

I get the following error

ActionController::InvalidCrossOriginRequest:
        Security warning: an embedded <script> tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.

This same error led to me using xhr :get in the first place, as per Rail 4.1 upgrade notes. I am now questioning my assumptions about what is happening here, and whether I do indeed "know what I'm doing"!

Is the correct way to resolve this error in this context to explicitly disable the Rails CSRF token for this action? i.e.,

# my_embeddable_controller.rb
protect_from_forgery except: :index

And if so, what was the previous xhr :get syntax doing that enabled requests to avoid cross-origin errors?

0 Answers
Related