17

It says there's an unexpected token in my params.

"ActionDispatch::Http::Parameters::ParseError: 765: unexpected token at 'conversation_identifier[participant_list][]=2&conversation_identifier[participant_list][]=1"

A version of the test with magic numbers for clarity:

let(:headers) do
  { 'HTTP_CURRENT_USER_ID' => 2,
    'Content-Type'         => 'application/json' }
end
let(:params) { { conversation_identifier: { participant_list: [1, 2] } }

it 'is getting testy' do
  post resource_url, params: params, headers: headers
  assert_equal 201, response.status
end

Now here's what's weird. It has no trouble parsing those params if I give it no headers.

Adamantish
  • 1,888
  • 2
  • 20
  • 23

2 Answers2

42

Removing the 'Content-Type' => 'application/json' solved the problem.

Finally remembered that ActionDispatch uses the headers to know how to parse the params. 'Content-Type' => 'application/json' is a standard piece of boilerplate that's ok to throw around with GET requests and query params but not with POST when used this way.

Adamantish
  • 1,888
  • 2
  • 20
  • 23
  • 2
    Thank you for posting this - I felt like I was taking crazy pills. You saved me – jstafford Dec 18 '19 at 00:20
  • 1
    This is not the correct answer. Instead of removing the `Content-Type` you should post a json instead a ruby hash in your request spec – DenicioCode Mar 02 '21 at 12:34
  • @DenniJensen According to the docs you're right https://relishapp.com/rspec/rspec-rails/docs/request-specs/request-spec#providing-json-data. `params.to_json` it seems. Going to verify when I get a moment and update the answer. – Adamantish Jul 09 '21 at 17:35
8

In case you still want 'Content-Type' => 'application/json': You should pass params to raw_post and call #to_json on the params that you pass.

Like:

    let(:raw_post) { params.to_json }
hstn
  • 113
  • 2
  • 7