Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@covard

This comment has been minimized.

Copy link

@covard covard commented Oct 4, 2017

Have you been able to get the headers to work in your test? I have been banging my head against this test. If I inspect the headers I can see them in there but if I try to inspect the keys it returns nil.

@thomasedwards

This comment has been minimized.

Copy link

@thomasedwards thomasedwards commented Dec 18, 2017

Thanks for this – exactly what I was looking for.

@mrhead

This comment has been minimized.

Copy link

@mrhead mrhead commented Jul 31, 2018

You don't have to set content type manually, instead of that you can use as: option:

post some_url, params: { foo: "bar" }, as: :json
@qrush

This comment has been minimized.

Copy link

@qrush qrush commented Jan 22, 2019

This was helpful thanks!

@wxgeorge

This comment has been minimized.

Copy link

@wxgeorge wxgeorge commented Mar 29, 2019

👍 to as: :json.

I have been searching for this for a long time!

👍 @mrhead!!

@BugBuster99

This comment has been minimized.

Copy link

@BugBuster99 BugBuster99 commented Aug 11, 2020

This was helpful!!! Thankss!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.