How rspec validates HTTP requests with body and headers

I am using rails4 + rspec 3. I want to make HTTP calls and pass both parameters (for example, JSON body or request string) as well as HTTP headers. I was able to go through one of these two, but not both.

when i try something like:

post api_v1_post_path(@myid), {} , {"X-Some-Header" => "MyValue"} 

it works fine and the headers are fine, but if I am something like:

post api_v1_post_path(@myid), {"myparam" => "myvalue"} , {"X-Some-Header" => "MyValue"} 

I get the following error:

Failure/Error: post api_v1_post_path(@myid), {"myparam" =>"myvalue"}, headers
 ActionDispatch::ParamsParser::ParseError:
   795: unexpected token at 'myparam'

Any ideas?

+4
source share
1 answer

It seems that the POST parameters are expected to be JSON encoded. 795: unexpected token at 'myparam'occurs when an application tries to JSON decode parameters that are not encoded.

Use .to_jsonwith post options.

post api_v1_post_path(@myid), {"myparam" => "myvalue"}.to_json , {"X-Some-Header" => "MyValue"}

You can use let:

describe 'Test' do
  let( :params  ){{ myparam: 'myvalue' }}
  let( :headers ){{ 'X-Some-Header' => 'MyValue' }}

  it 'succeeds' do
    post api_v1_post_path(@myid), params.to_json , headers
+4

Source: https://habr.com/ru/post/1539961/


All Articles