Search code examples
ruby-on-railsrspec-rails

Rspec GET request not correctly returning values from database


I'm writing tests for an API that should send information from the database (PostreSQL) from a GET request. However my RSpec GET request refuse to return any values.

This is the test :

describe FullTextController do
  context 'when doing a simple search', :type => :request do
    it 'return the correct results' do
      create(:etablissement, nom: "foobarcompany")
      create(:etablissement, nom: "foobarcompany2")
      create(:etablissement, nom: "foobarcompany3")
      create(:etablissement, nom: "foobarcompany4")
      sleep 2
      get "/full_text/:id", :params => { id: 'foobarcompany' }

      expect(body_as_json).to match({
        total_results: 1,
        total_pages: 1,
        per_page: 10,
        page: 1,
        etablissement: 1,
        })
    end
  end

It is supposed to test this controller :

class FullTextController < ApplicationController
  def show

    page = params[:page] || 1

    search = Etablissement.search do
      fulltext params[:id]
      paginate page: page, per_page: 10
    end

    results = search.results

      results_payload = {
        total_results: search.total,
        total_pages: results.total_pages,
        per_page: results.per_page,
        page: page,
        etablissement: results
      }

      render json: results_payload, status: 200
    end
  end

  def full_text_params
    params.permit(:id, :page)
  end
end

The routes from config/routes.rb :

Rails.application.routes.draw do
  get 'siret/:id' => 'siret#show'
  get 'full_text/:id' => 'full_text#show'
end

The output from the test :

       expected {"total_results"=>0, "total_pages"=>0, "per_page"=>10, "page"=>1, "etablissement"=>[]} to match {:total_results=>1, :total_pages=>1, :per_page=>10, :page=>1, :etablissement=>1}
   Diff:
   @@ -1,6 +1,6 @@
   -:etablissement => 1,
   -:page => 1,
   -:per_page => 10,
   -:total_pages => 1,
   -:total_results => 1,
   +"etablissement" => [],
   +"page" => 1,
   +"per_page" => 10,
   +"total_pages" => 0,
   +"total_results" => 0,

It should find at least 1 result, but it keeps showing zero. I already checked that I was on the correct test database and that the created models (etablissement) were in the database.


Solution

  • The get call should follow the following structure : full_text/:id with the :id part being replace by the actual id you want to pass. Rails will consider the id part as a params in the controller. It is actually NOT a param from the point of view of the url (params are what come after ?, like ?param1=value1&param2=value2)

    What you do here is get "/full_text/:id", :params => { id: 'foobarcompany' } which translates into /full_text/:id?id=foobarcompany

    You want to use get "/full_text/foobarcompany" instead