Rails functional test: sending URL query parameters in POST request

前端 未结 5 1520
栀梦
栀梦 2021-02-19 20:55

I\'m sending a POST request in a Rails functional test like this:

post :create, collection: { name: \'New Collection\' }

collection

相关标签:
5条回答
  • 2021-02-19 21:44

    A little background first to clarify things: although a request cannot be both GET and POST at the same time, there is nothing stopping you from using both the query string and body form data when using POST. You can even have a POST with all parameters in the query string and an empty body, though this sounds quite unusual.

    Rails supports this scenario and indeed you can easily send a form using a POST request and still have query in the form's action. The query will be accessible with request.GET hash (which is an alias of query_string), while the POST body params with the request.POST hash (an alias of request_parameters). The params hash is actually constructed from the combined GET and POST hashes.

    However, from my research it seems that Rails does not support passing query string in POST requests in functional controller tests. Although I could not find anything regarding this in any documentation or among known issues on github, the source code is quite clear. In the following text, I'm assuming that you use Rails 4.

    Why it does not work

    The problem with functional controller tests is that they don't use real requests / responses but they simulate the HTTP handshake: the request is mocked up, its parameters filled in appropriate places and the given controller action is simply called as a normal ruby method. All of this is done in the action_controller/test_case classes.

    As it turns out, this simulation is not working in your particular case, due to two reasons:

    1. The parameters passed in when running the test are always handed over either to the request_parameters, i.e. the request.POST hash when using a post request or to the query_string (i.e. request.GET) for get test requests. There is no way for both of these hashes to be set during a single test run.

      This actually makes some sense as the get, post, etc. helpers in functional tests accept only a single hash of params so the internal test code cannot know how to separate them into the two hashes.

    2. It is true that one can set up the request before running the test using the @request variable, but only to a certain extent, you can set headers, for example. But you cannot set internal attributes of the request, because they are recycled during the test run. The recycling is done here and it resets all internal variables of the request object and the underlying rack request object. So if you try to set up the request GET parameters like this @request.GET[:api_key] = 'my key', it won't have any effect as the internal variables representing this hash will get wiped during recycling.

    Solutions / workarounds

    • Give up functional testing and choose integration tests instead. Integration tests allow to set the rack environment variables separately from the main parameters. The following integration test passes the QUERY_STRING rack env variable besides the normal post body params and should work flawlessly:

      class CollectionsTest < ActionDispatch::IntegrationTest
        test 'foo' do
          post collections_path, { collection: { name: 'New Collection' } }, 
                                 { "QUERY_STRING" => "api_key=my_api_key" }
      
          # this proves that the parameters are recognized separately in the controller
          # (you can test this in you controller as well as here in the test):
          puts request.POST.inspect
          # => {"collection"=>{"name"=>"New Collection"}}
          puts request.GET.inspect
          # => {"api_key"=>"my_api_key"}
        end
      end
      

      You can still use most of the features from functional tests in your integration tests. E.g. you can test for assigned instance variables in the controller with the assigns hash.

      The transition argument is supported also by the fact that Rails 5 will deprecate functional controller tests in favor of integration testing and since Rails 5.1 these functional tests support will be moved out to a separate gem.

    • Try Rails 5: although functional tests will be deprecated, its source code seems to have been heavily rewritten in the rails master and e.g. recycling of the request is not used any more. So you might give it a try and try to set the internal variables of the request during test setup. I have not tested it though.

    • Of course, you can always try to monkey-patch the functional test so that it supports separate params for the query_string and request_parameters hashes to be defined in tests.

    I'd go the integration tests route :).

    0 讨论(0)
  • 2021-02-19 21:44

    The 2nd argument to post is a hash of all the params you'll receive in the controller. Just do this:

    post :create, collection: { name: 'New Collection' }, more_params: 'stuff', and_so_on: 'things'
    

    Those params will be available in the controller:

    params[:and_so_on] == 'things'
    
    0 讨论(0)
  • 2021-02-19 21:47

    You want to send a POST request:

    I'm sending a POST request in a Rails functional test like this:

    But you want to retrieve data from a GET request:

    But, :api_key never appears in the request.GET hash on the server.

    A request cannot be GET and POST at the same time, if you are sending a POST request and pass parameters in the query string then you would have those parameter values available on a POST request, GET just won't have anything.

    Then:

    @request.GET[:api_key] = 'my key'
    post :create, collection: { name: 'New Collection' }
    

    You are modifying the GET values on the request, but then you actually send a POST request which means that when the post method gets called and the request is sent to the server only what you sent on the POST will be available. Just send the api key bundled with the POST request (could be inside the collection hash for that matter)

    0 讨论(0)
  • 2021-02-19 21:52

    I assume that the controller is named CollectionsController, and its route to create action is /collections (if not, you just have to adapt the example bellow)

    And I also assume you are in a request spec

    This should work:

    post '/collections?api_key=my_key', collection: { name: 'New Collection' }
    
    0 讨论(0)
  • 2021-02-19 21:58

    This is also a problem when testing POST actions with RSpec (v3.4).

    A workaround is to mock the return value of request.GET or request.query_string methods.

    it "should recognise a query parameter in post action" do
      allow(subject.request).to receive(:query_string).and_return("api_key=my%20key")  
      @params = {collection: { name: 'New Collection' }}
    
    
      expect(subject.request.query_string).to eq "api_key=my%20key"
    
      post :create, @params
    end
    
    0 讨论(0)
提交回复
热议问题