Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Testing XHR with Post data

I'm just dipping my toes into Ruby and Rails and trying to get my head the whole BDD thing. I have a page that does an AJAX POST back to a controller that has a method called "sort" and passes along an array of id's like this

["song-section-5", "song-section-4", "song-section-6"]

I want to write a test for this so I came up with something like this:

test "should sort items" do
  xhr :post, :sort
end

But can't figure out how to pass along the array. Any help?

like image 482
Dana Avatar asked Jun 18 '11 08:06

Dana


2 Answers

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"] }
like image 160
monocle Avatar answered Sep 19 '22 12:09

monocle


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
like image 42
odlp Avatar answered Sep 17 '22 12:09

odlp