Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexanmtz/b474305176140f6dd707f56d9698dcb3 to your computer and use it in GitHub Desktop.
Save alexanmtz/b474305176140f6dd707f56d9698dcb3 to your computer and use it in GitHub Desktop.
PUT or POST JSON in a Rails 5 ActionDispatch::IntegrationTest

In Rails 5, the preferred base class for testing controllers is ActionDispatch::IntegrationTest.

If you have an API that receives parameters as JSON request bodies, here are some helper methods to facilitate testing:

class ActionDispatch::IntegrationTest
  def put_json(path, obj)
    put path, params: obj.to_json, headers: { 'CONTENT_TYPE' => 'application/json' }
  end

  def post_json(path, obj)
    post path, params: obj.to_json, headers: { 'CONTENT_TYPE' => 'application/json' }
  end
end

Sample usage:

class MyControllerTest < ActionDispatch::IntegrationTest
  test 'creating a foo' do
    post_json foos_path, foo: { attr_1: 'bar', attr_2: 'baz' }
    assert_response :created
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment