Rspec GET请求未正确返回数据库中的值

时间:2017-05-28 06:47:44

标签: ruby-on-rails rspec-rails

我正在为API编写测试,该API应该从GET请求发送数据库(PostreSQL)的信息。 但是我的RSpec GET请求拒绝返回任何值。

这是测试:

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

应该测试这个控制器:

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

来自config / routes.rb的路由:

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

测试的输出:

       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,

它应该找到至少1个结果,但它一直显示为零。 我已经检查过我在正确的测试数据库上,并且创建的模型(etablissement)在数据库中。

1 个答案:

答案 0 :(得分:0)

get调用应遵循以下结构:full_text/:id:id部分将替换为您要传递的实际id。 Rails会将id部分视为控制器中的参数。从网址的角度来看,它实际上不是一个参数(参数是后来的?,如?param1=value1&param2=value2

您在此处执行的操作是get "/full_text/:id", :params => { id: 'foobarcompany' },其转换为/full_text/:id?id=foobarcompany

您想要使用get "/full_text/foobarcompany"