Rails Testing XHR with Post data

For me, using RSpec 3.6 and Rails 5.1 the previous answer fails:

xhr :post, :index

# => NoMethodError: undefined method `xhr' for #<RSpec::ExampleGroups::XController::Index::AJAXRequest:0x007fd9eaa73778>

Rails 5.0+

Instead try setting xhr: true like this:

post :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

From the Rails source code

def xml_http_request(request_method, action, parameters = nil, session = nil, flash = nil)

The third input to the method is "parameters". These are the params sent to your controller.

xhr :post, :sort, { :ids => ["song-section-5", "song-section-4", "song-section-6"] }