Rails functional test: sending URL query parameters in POST request

16,091

Solution 1

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 :).

Solution 2

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' }

Solution 3

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'

Solution 4

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)

Share:
16,091
alexantd
Author by

alexantd

Updated on June 18, 2022

Comments

  • alexantd
    alexantd almost 2 years

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

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

    collection gets sent as JSON-encoded form data, as expected.

    What I can't figure out is how to add a query to the URL. The documentation says that I can access the request object and modify it before it gets sent. So I tried this:

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

    But, :api_key never appears in the request.GET hash on the server. (It does when I send it though another HTTP client, though.)

  • alexantd
    alexantd almost 10 years
    Unfortunately, adding more arguments to post will simply add keys to the JSON object in the request body. I need to add to the URL query, e.g. http://../?key=value
  • DiegoSalazar
    DiegoSalazar almost 10 years
    How are you retrieving the values in your controller?
  • alexantd
    alexantd almost 10 years
    With request.GET and request.POST. I know that the post arguments from the test will be present in the params hash on the server, but in this case, I'm building an API that needs to be consistent about how it accepts an api_key no matter what the request type (GET, POST, PATCH, etc.).
  • alexantd
    alexantd almost 10 years
    "Minitest::UnexpectedError: ActionController::UrlGenerationError: No route matches" (this is Rails 4.1/Minitest 5.1 btw)
  • Benj
    Benj almost 10 years
    Ah ok, I don't know about minitest. In Rspec there is 3 different types of test you can do to your controller. In one of them, the "request specs", you can do that because it go through the Rails routing stack. And that's what you need here. So what about minitest, is there this kind of test environment available?
  • bonzo
    bonzo over 6 years
    I tried this but it did not work. What worked for me was stubbing `query_parameters' to return a hash of the params I would have passed in the query string.