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?
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"] }
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>
Instead try setting xhr: true
like this:
post :index, xhr: true
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With