簡體   English   中英

使用 rspec 測試 API 端點

[英]Using rspec to test an API endpoint

我有這個 api 端點 wot 從我的數據庫中獲取所有博客,這些博客在用戶傳遞 api_key 時起作用。 這工作正常,現在我正在嘗試測試這個端點。

路線:

Rails.application.routes.draw do
  get 'blogs', to: 'blogs#index'
end

博客控制器:

class BlogsController < ApplicationController
  def index
    if params[:api_key]
      user = User.find_by(api_key: params[:api_key])
      if user.present?
        @blogs = Blog.all
        return render json: @blogs, status: :ok   
      end         
    end
    render json: { error: "Unauthorized!" }, status: :bad_request
  end
end

我是 rspec 和測試的新手,我看了幾個視頻和教程,這就是我到目前為止所擁有的:

spec/requests/blogs_spec.rb

require 'rails_helper'

RSpec.describe 'Blogs API', type: :request do
  let!(:blogs) { Blog.limit(10) }

  describe 'GET /blogs' do
    before { get '/blogs' }
    
    it 'returns status code 400' do
      expect(response).to have_http_status(400)
    end

    context 'when the request is valid' do
      before { get '/blogs', params: { api_key: '123123'} }

      it 'returns status code 400' do
        expect(response).to have_http_status(200)
      end
    end
  end
end

我似乎無法使最后一個測試工作,我不知道為什么。 我的猜測是我沒有正確傳遞api_key ,但我不知道如何

 1) Blogs API GET /blogs when the request is valid returns status code 400
     Failure/Error: expect(response).to have_http_status(200)
       expected the response to have status code 200 but it was 400
     # ./spec/requests/blogs_spec.rb:28:in `block (4 levels) in <top (required)>'

好的,因此根據您的問題 + 評論,我可以假設您正在test環境中運行您的測試,但您希望找到development數據庫中存在的User

工廠機器人

您可能想使用FactoryBot為您的測試套件創建記錄。

添加到您的 Gemfile:

group :development, :test do
  gem 'factory_bot_rails'
end

rails_helper.rb ,添加:

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end

現在您應該創建您的User工廠。 使用以下內容創建一個新文件spec/factories/user.rb

FactoryBot.define do
  factory :user do
    api_key { '123123' }
    # You should define every any other required attributes here so record can be created
  end
end

最后,在您的規范文件中:

    ....

    context 'when the request is valid' do
      before { get '/blogs', params: { api_key: user.api_key} }
      let!(:user) { create(:user) }

      it 'returns status code 200' do
        expect(response).to have_http_status(200)
      end
    end

    ...

現在你的測試應該通過了。 請注意,在測試數據庫中也沒有創建Blog ,因此:

let!(:blogs) { Blog.limit(10) }

將返回一個空數組。 您還需要創建一個Blog工廠,並創建如下博客:

let!(:blogs) { create_list(:blog, 2) }

獎金

一旦你開始改進你的測試,你可能想看看ActiveRecord 的FakerDatabase Cleaner

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM