【问题标题】:How do you handle bad requests with RSpec tests in Rails?你如何在 Rails 中使用 RSpec 测试处理错误请求?
【发布时间】:2019-12-21 21:44:51
【问题描述】:

在我的测试数据库中,我有评论,我正在我的仅 API 的 Rails 5 应用程序中进行 API 调用。

到目前为止,我已经为我的索引编写了测试并显示了 ReviewController 的操作。

如何处理错误/错误请求处理?例如,如果有人试图去一个不存在的路线,或者如果有人试图导航到一个没有现有 id 的显示路线,那么在 RSpec 中是如何完成的?

# spec/controllers/api/v1/reviews_controller_spec.rb
require 'rails_helper'

RSpec.describe Api::V1::ReviewsController do
  describe "GET #index" do
    before do
      get :index
    end

    it "returns HTTP Success" do
      expect(response).to have_http_status(:success)
    end

    it "JSON body response contains expected review attributes" do
      json_response = JSON.parse(response.body)
      json_response["status"].should == "SUCCESS"
    end
  end

  describe "GET #show" do
    before do
      get :show, params: { id: 1 }
    end

    it "returns HTTP Success" do
      expect(response).to have_http_status(:success)
    end

    it "JSON body response contains expected review attributes" do
      json_response = JSON.parse(response.body)
      json_response["status"].should == "SUCCESS"
    end
  end
end

评论控制器:

# spec/controllers/api/v1/reviews_controller.rb
module Api
  module V1
    class ReviewsController < ApplicationController
      def index
        @reviews = Review.order(created_at: :desc)
        render json: { status: 'SUCCESS', message: 'loaded reviews', data: @reviews }
      end

      def show
        @review = Review.find(params[:id])
        render json: { status: 'SUCCESS', message: 'loaded the review', data: @review }
      end

      private

      def review_params
        params.require(:review).permit(:title, :star, :content, :name, :date)
      end
    end
  end
end

【问题讨论】:

  • 可以查看http状态是否为:bad_request

标签: ruby-on-rails ruby testing rspec


【解决方案1】:

在控制器测试中,您可以指定控制器在 id 不存在时引发 ActiveRecord::RecordNotFound

describe "GET #show" do
  context "with a valid id" do
    before do
      get :show, params: { id: 1 }
    end

    it "returns HTTP Success" do
      expect(response).to have_http_status(:success)
    end

    it "JSON body response contains expected review attributes" do
      json_response = JSON.parse(response.body)
      json_response["status"].should == "SUCCESS"
    end
  end

  context "with an invalid id" do
    it "raises an error" do
      expect { 
        get :show, params: { id: "invalid-identifier" }
      }.to raise_error ActiveRecord::RecordNotFound
    end
  end
end

请注意,当控制器在 production 环境中引发 ActiveRecord::RecordNotFound 时,Ruby on Rails 将返回 404 (not found) - 如果默认值没有更改。在Rails Guides 中阅读有关此行为的更多信息。

【讨论】:

    猜你喜欢
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2012-06-22
    • 1970-01-01
    相关资源
    最近更新 更多