How to send raw post data in a Rails functional test?

后端 未结 12 1626
感情败类
感情败类 2020-12-13 12:07

I\'m looking to send raw post data (e.g. unparamaterized JSON) to one of my controllers for testing:

class LegacyOrderUpdateControllerTest < ActionControl         


        
12条回答
  •  天命终不由人
    2020-12-13 12:59

    As of Rails 4.1.5, this was the only thing that worked for me:

    class LegacyOrderUpdateControllerTest < ActionController::TestCase
      def setup
        @request.headers["Content-Type"] = 'application/json'
      end
    
      test "sending json" do
        post :index, '{"foo":"bar", "bool":true}'.to_json, { account_id: 5, order_id: 10 }
      end
    end
    

    for a url at /accounts/5/orders/10/items. This gets the url params conveyed as well as the JSON body. Of course, if orders is not embedded then you can leave off the params hash.

    class LegacyOrderUpdateControllerTest < ActionController::TestCase
      def setup
        @request.headers["Content-Type"] = 'application/json'
      end
    
      test "sending json" do
        post :index, '{"foo":"bar", "bool":true}'.to_json
      end
    end
    

提交回复
热议问题