Search code examples
ruby-on-railsminitest

Why does my 'get' request turn into a 'post' request when I add params (rails, minitest)?


I'm trying to write an paginated index action in a rails app. This is my controller code

def index
  @pokemons = Pokemon.all.limit(params[:limit]).offset(params[:offset])
end

This works perfectly in my development server when I make requests through a browser.

In my tests, however, I'm having trouble calling the index action.

When I run my test as below, a GET request is made that's routed to #index.

test "should return paginated index" do
  get pokemons_url, as: :json
  assert_response :success
end

However as soon as I add params related to pagination, like so...

test "should return paginated index" do
  get pokemons_url, params: {limit: 10, offset: 0}, as: :json
  assert_response :success
end

...the request received by my server becomes a POST instead of a GET and it's routed to my #create action.

Here's my config/routes.rb:

Rails.application.routes.draw do
  resources :pokemons
end

and here's the relevant output from rails routes:

                             pokemons GET    /pokemons(.:format)                                                                               pokemons#index
                                     POST   /pokemons(.:format)                                                                               pokemons#create
                             pokemon GET    /pokemons/:id(.:format)                                                                           pokemons#show
                                     PATCH  /pokemons/:id(.:format)                                                                           pokemons#update
                                     PUT    /pokemons/:id(.:format)                                                                           pokemons#update
                                     DELETE /pokemons/:id(.:format)                                                                           pokemons#destroy

Why does adding params to the 'get' method in Minitest turn my GET request into a POST request? How can I send a GET from Minitest that includes my pagination parameters?


Solution

  • If the parameters are intended to be simple query string parameters you should pass them to the routing helper:

    test "should return paginated index" do
      get pokemons_url(limit: 10, offset: 0), as: :json
      assert_response :success
    end