Why is Accept: application/json and Content-Type: application/json causing issues in this test?What is JSON and why would I use it?What is the correct JSON content type?Why does Google prepend while(1); to their JSON responses?Why can't Python parse this JSON data?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?How do you set the Content-Type header for an HttpClient request?Authenticating to an API with a tokenWSO2 not allowing '@' symbol as input parameter in methodsHow to generate authorization request header?use HttpClient to set the Content-Type to “application/json” and add object to the body

Plot twist where the antagonist wins

Grammar Question Regarding "Are the" or "Is the" When Referring to Something that May or May not be Plural

Is it possible to build VPN remote access environment without VPN server?

Why is this Simple Puzzle impossible to solve?

Adding spaces to string based on list

What was the idiom for something that we take without a doubt?

Is it possible to play as a necromancer skeleton?

Image processing: Removal of two spots in fundus images

Does the unit of measure matter when you are solving for the diameter of a circumference?

Is the Indo-European language family made up?

How to use " shadow " in pstricks?

Count rotary dial pulses in a phone number (including letters)

Why are C64 games inconsistent with which joystick port they use?

Why do most published works in medical imaging try to reduce false positives?

Popcorn is the only acceptable snack to consume while watching a movie

Is the Starlink array really visible from Earth?

What are these arcade games in Ghostbusters 1984?

Who will lead the country until there is a new Tory leader?

What is quasi-aromaticity?

What is a Centaur Thief's climbing speed?

Make 24 using exactly three 3s

Why do Ryanair allow me to book connecting itineraries through a third party, but not through their own website?

Were pens caps holes designed to prevent death by suffocation if swallowed?

When and what was the first 3D acceleration device ever released?



Why is Accept: application/json and Content-Type: application/json causing issues in this test?


What is JSON and why would I use it?What is the correct JSON content type?Why does Google prepend while(1); to their JSON responses?Why can't Python parse this JSON data?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?How do you set the Content-Type header for an HttpClient request?Authenticating to an API with a tokenWSO2 not allowing '@' symbol as input parameter in methodsHow to generate authorization request header?use HttpClient to set the Content-Type to “application/json” and add object to the body






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I have the following test:



require 'rails_helper'

RSpec.describe 'User management', :type => :request do
before do
@expected_number_of_users = 3
end

context 'an authenticated user with admin privileges' do
before do
# This username/password combo is in my fixtures
@headers = login_user 'scottj', '123456'
end

context 'when at least a username, name, role, and email address are passed as inputs' do
before do
@new_user_details =
:username => 'stitch',
:name => 'Stitch',
:role => :admin,
:email => 'stitch@disney.com'

end

it 'should create a new user' do
post users_path, headers: @headers, params: @new_user_details
expect(response).to have_http_status(:ok)

expect(json.username).to eq('stitch')
expect(json.name).to eq('Stitch')
expect(json.role).to eq(:admin.to_s)
expect(json.email).to eq('stitch@disney.com')
expect(json.password).to_not be_nil
end
end
end
end


With the following login_support.rb file:



module LoginSupport
def json_api_headers

"Content-Type": 'application/json',
"Accept": 'application/json'

end

def login_user(username, password)
combined_login_password = username + ":" + password
encoded_username_password = Base64.encode64(combined_login_password)
headers =
'X-Api-Key': Client.find_by_id(1234).api_key,
'Authorization': 'Basic ' + encoded_username_password
.merge(json_api_headers)

post '/login', headers: headers

user = JSON.parse(response.body, object_class: OpenStruct)


'Authorization': 'Bearer ' + user.auth_token

end
end


This test passes as expected, but when I change the return type of login_user to be (i.e. change the last three lines of that function):




'Authorization': 'Bearer ' + user.auth_token
.merge(json_api_headers)


Now, when I run the test, I get the error:



ActionDispatch::ParamsParser::ParseError: 765: unexpected token at 'username=stitch&name=Stitch&role=admin&email=jaywir3%40gmail.com'


It seems to me that the more correct version of the headers, since my API is both expecting to receive the body of a POST request in JSON form, as well as returning JSON, is with these headers in place. It looks to me that the POST request with those headers specified, though, is trying to pass the body of the request as query parameters.



Is there something I'm doing wrong? Should I just leave the Accept and Content-Type headers off of my requests when testing?










share|improve this question




























    1















    I have the following test:



    require 'rails_helper'

    RSpec.describe 'User management', :type => :request do
    before do
    @expected_number_of_users = 3
    end

    context 'an authenticated user with admin privileges' do
    before do
    # This username/password combo is in my fixtures
    @headers = login_user 'scottj', '123456'
    end

    context 'when at least a username, name, role, and email address are passed as inputs' do
    before do
    @new_user_details =
    :username => 'stitch',
    :name => 'Stitch',
    :role => :admin,
    :email => 'stitch@disney.com'

    end

    it 'should create a new user' do
    post users_path, headers: @headers, params: @new_user_details
    expect(response).to have_http_status(:ok)

    expect(json.username).to eq('stitch')
    expect(json.name).to eq('Stitch')
    expect(json.role).to eq(:admin.to_s)
    expect(json.email).to eq('stitch@disney.com')
    expect(json.password).to_not be_nil
    end
    end
    end
    end


    With the following login_support.rb file:



    module LoginSupport
    def json_api_headers

    "Content-Type": 'application/json',
    "Accept": 'application/json'

    end

    def login_user(username, password)
    combined_login_password = username + ":" + password
    encoded_username_password = Base64.encode64(combined_login_password)
    headers =
    'X-Api-Key': Client.find_by_id(1234).api_key,
    'Authorization': 'Basic ' + encoded_username_password
    .merge(json_api_headers)

    post '/login', headers: headers

    user = JSON.parse(response.body, object_class: OpenStruct)


    'Authorization': 'Bearer ' + user.auth_token

    end
    end


    This test passes as expected, but when I change the return type of login_user to be (i.e. change the last three lines of that function):




    'Authorization': 'Bearer ' + user.auth_token
    .merge(json_api_headers)


    Now, when I run the test, I get the error:



    ActionDispatch::ParamsParser::ParseError: 765: unexpected token at 'username=stitch&name=Stitch&role=admin&email=jaywir3%40gmail.com'


    It seems to me that the more correct version of the headers, since my API is both expecting to receive the body of a POST request in JSON form, as well as returning JSON, is with these headers in place. It looks to me that the POST request with those headers specified, though, is trying to pass the body of the request as query parameters.



    Is there something I'm doing wrong? Should I just leave the Accept and Content-Type headers off of my requests when testing?










    share|improve this question
























      1












      1








      1


      1






      I have the following test:



      require 'rails_helper'

      RSpec.describe 'User management', :type => :request do
      before do
      @expected_number_of_users = 3
      end

      context 'an authenticated user with admin privileges' do
      before do
      # This username/password combo is in my fixtures
      @headers = login_user 'scottj', '123456'
      end

      context 'when at least a username, name, role, and email address are passed as inputs' do
      before do
      @new_user_details =
      :username => 'stitch',
      :name => 'Stitch',
      :role => :admin,
      :email => 'stitch@disney.com'

      end

      it 'should create a new user' do
      post users_path, headers: @headers, params: @new_user_details
      expect(response).to have_http_status(:ok)

      expect(json.username).to eq('stitch')
      expect(json.name).to eq('Stitch')
      expect(json.role).to eq(:admin.to_s)
      expect(json.email).to eq('stitch@disney.com')
      expect(json.password).to_not be_nil
      end
      end
      end
      end


      With the following login_support.rb file:



      module LoginSupport
      def json_api_headers

      "Content-Type": 'application/json',
      "Accept": 'application/json'

      end

      def login_user(username, password)
      combined_login_password = username + ":" + password
      encoded_username_password = Base64.encode64(combined_login_password)
      headers =
      'X-Api-Key': Client.find_by_id(1234).api_key,
      'Authorization': 'Basic ' + encoded_username_password
      .merge(json_api_headers)

      post '/login', headers: headers

      user = JSON.parse(response.body, object_class: OpenStruct)


      'Authorization': 'Bearer ' + user.auth_token

      end
      end


      This test passes as expected, but when I change the return type of login_user to be (i.e. change the last three lines of that function):




      'Authorization': 'Bearer ' + user.auth_token
      .merge(json_api_headers)


      Now, when I run the test, I get the error:



      ActionDispatch::ParamsParser::ParseError: 765: unexpected token at 'username=stitch&name=Stitch&role=admin&email=jaywir3%40gmail.com'


      It seems to me that the more correct version of the headers, since my API is both expecting to receive the body of a POST request in JSON form, as well as returning JSON, is with these headers in place. It looks to me that the POST request with those headers specified, though, is trying to pass the body of the request as query parameters.



      Is there something I'm doing wrong? Should I just leave the Accept and Content-Type headers off of my requests when testing?










      share|improve this question














      I have the following test:



      require 'rails_helper'

      RSpec.describe 'User management', :type => :request do
      before do
      @expected_number_of_users = 3
      end

      context 'an authenticated user with admin privileges' do
      before do
      # This username/password combo is in my fixtures
      @headers = login_user 'scottj', '123456'
      end

      context 'when at least a username, name, role, and email address are passed as inputs' do
      before do
      @new_user_details =
      :username => 'stitch',
      :name => 'Stitch',
      :role => :admin,
      :email => 'stitch@disney.com'

      end

      it 'should create a new user' do
      post users_path, headers: @headers, params: @new_user_details
      expect(response).to have_http_status(:ok)

      expect(json.username).to eq('stitch')
      expect(json.name).to eq('Stitch')
      expect(json.role).to eq(:admin.to_s)
      expect(json.email).to eq('stitch@disney.com')
      expect(json.password).to_not be_nil
      end
      end
      end
      end


      With the following login_support.rb file:



      module LoginSupport
      def json_api_headers

      "Content-Type": 'application/json',
      "Accept": 'application/json'

      end

      def login_user(username, password)
      combined_login_password = username + ":" + password
      encoded_username_password = Base64.encode64(combined_login_password)
      headers =
      'X-Api-Key': Client.find_by_id(1234).api_key,
      'Authorization': 'Basic ' + encoded_username_password
      .merge(json_api_headers)

      post '/login', headers: headers

      user = JSON.parse(response.body, object_class: OpenStruct)


      'Authorization': 'Bearer ' + user.auth_token

      end
      end


      This test passes as expected, but when I change the return type of login_user to be (i.e. change the last three lines of that function):




      'Authorization': 'Bearer ' + user.auth_token
      .merge(json_api_headers)


      Now, when I run the test, I get the error:



      ActionDispatch::ParamsParser::ParseError: 765: unexpected token at 'username=stitch&name=Stitch&role=admin&email=jaywir3%40gmail.com'


      It seems to me that the more correct version of the headers, since my API is both expecting to receive the body of a POST request in JSON form, as well as returning JSON, is with these headers in place. It looks to me that the POST request with those headers specified, though, is trying to pass the body of the request as query parameters.



      Is there something I'm doing wrong? Should I just leave the Accept and Content-Type headers off of my requests when testing?







      ruby-on-rails json api






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 24 at 5:17









      jwir3jwir3

      3,80343674




      3,80343674






















          0






          active

          oldest

          votes












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55320939%2fwhy-is-accept-application-json-and-content-type-application-json-causing-issue%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55320939%2fwhy-is-accept-application-json-and-content-type-application-json-causing-issue%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript