Rails Testing XHR with Post data

Viewed 11263

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?

3 Answers

The answer

test "should sort items" do
  post path_to_your_sort_action, params: { ids: ["song-section-5", "song-section-4", "song-section-6"] }, xhr: true, 
end
# using Rails +6 and minitest

Proof?

  • Here are links to the source code, the first leads to the second, which contains the answer you are looking for.

  • Explanation: The modern Rails stack prefers using integration tests rather than controller tests - so you'll be using ActionDispatch::IntegrationTest. If you want to send a post request simply pass in xhr: true. Check the source code above.

Related