0
我正在編寫一個測試API,它應該從GET請求中發送來自數據庫(PostreSQL)的信息。 但是,我的RSpec GET請求拒絕返回任何值。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
從配置/ 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)在數據庫中。
您是否嘗試在測試用例中設置'binding.pry'。這個測試用例是否在控制器中失敗以選擇'etablissement'變量? –
我剛剛通過在GET請求後面添加'binding.pry'來檢查,如果我輸入「response」,那麼我得到空的響應,如果我鍵入'Etablissement.all',那麼我得到零。這很奇怪,因爲如果我在測試代碼中執行Etablissement請求,我會得到一個結果:'puts Etablissement.first.name'將返回「foobarcompany」 可悲的是,我從來沒有使用過binding.pry。你會建議我嘗試一下嗎? –
好的,如果問題在於''Etablissement'沒有保存到測試數據庫中,那麼當您執行'create(:etablissement')時,我會建議在調試時返回並檢查'etablissement.errors.full_messages'並檢查是否存在保存記錄時出現一些錯誤 –