ruby-on-rails 我怎样才能捕捉正确发生的错误?

j91ykkif  于 2023-01-22  发布在  Ruby
关注(0)|答案(2)|浏览(95)

目前,我捕获到如下错误not_found

def show
            begin
              @task = Task.find(params[:id])          
            rescue ActiveRecord::RecordNotFound => e
              render json: { error: e.to_s }, status: :not_found and return     
            end

并且rspec测试将类似于expect(response).to be_not_found,但是我不想在每个函数(更新、创建、销毁等)中都这样做(抢救ActiveRecord::RecordNotFound =〉e)
还有别的办法吗
比如这样

rescue_from ActiveRecord::RecordNotFound, with: :not_found

                      def not_found
                        respond_to do |format|
                          format.json { head :not_found }
                        end
                      end

但是我不知道我怎么用它来测试
我想用同样的方法测试

expect(response).to be_not_found
a0zr77ik

a0zr77ik1#

我认为您的原始实现使用错误节点是一个更好的响应,但您修改的更改是一个更好的处理方式,因此我建议通过以下方式将这两个概念结合起来

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, with: :not_found

  private 
    def not_found(exception) 
      respond_to do |format| 
        format.json do 
          # I expanded the response a bit but handle as you see fit
          render json: {
            error: {
              message: 'Record Not Found', 
              data: { 
                 record_type: exception.model,
                 id: exception.id
               } 
            }
          }, status: :not_found 
      end 
    end 
end

在这种情况下,您应该能够保持当前的测试,同时避免在每个请求中单独处理的需要。

nfeuvbwi

nfeuvbwi2#

您可以将以下代码添加到您的application_controller. rb中。

around_filter :catch_not_found #=> only:[:show, :edit]

def catch_not_found
  yield
rescue ActiveRecord::RecordNotFound => e
  respond_to do |format|
   format.json { render json: { error: e.to_s }, status: :not_found and return   } 
   format.html { redirect_to root_url, :flash => { :error => "Record not found." } and return }
  end 
end

下面是使用RSpec的测试用例的简单示例。根据您的需求进行修改。
人员_控制器.rb

def show
 @staff = Staff.find(params[:id])
end

R规范

let(:staff) { FactoryBot.create(:staff) }

describe "GET #show" do
  it "Renders show page for valid staff" do
    get :show, {:id => staff.to_param}
    expect(response).to render_template :show
  end
  it "redirects to root path on staff record not_found" do
    get :show, id: 100
    expect(response).to redirect_to(root_path)
  end
end

相关问题