rspec - How to test ActiveRecord::RecordNotFound?

前端 未结 2 693
死守一世寂寞
死守一世寂寞 2021-01-28 13:06

I have a method to update people\'s attribute, and it will rescue ActiveRecord::RecordNotFound if the people cannot be found. The method is:

  def u         


        
相关标签:
2条回答
  • 2021-01-28 13:31

    This is not a good solution to begin with. In Rails you want to use rescue_from to handle common errors on the controller level.

    class ApplicationController
      rescue_from ActiveRecord::RecordNotFound, with: :not_found
    
      def not_found
        respond_to do |format|
          format.json { head :404 }
        end
      end
    end
    

    This lets you use inheritance to DRY your code.

    render json: { error: 'Failed') }
    

    Is a huge anti-pattern. If the request failed you should tell the client by sending the correct HTTP status code. Don't reinvent the wheel. Especially not when your solution is a square wheel. If your JS relies on monkeying around with a json response to see if the request was a success or not you're doing it wrong.

    If you want to test that your controller handles a missing resource correctly you would do:

    let(:people) { create(:people) }
    let(:people_id) { people.id }
    let(:user) { people}
    
    it "returns the correct response code if the person cannot be found" do
      get '/people/notarealid'
      expect(response).to have_http_status :not_found
    end
    

    This does not use any stubbing and actually tests the implementation.

    0 讨论(0)
  • 2021-01-28 13:51

    you can try :

    let!(:error_failed) { { error: 'Failed' } }
    
    context 'when people is not found by params' do
      it 'return 404 and render json failed'
        null_object = double.as_null_object
        allow(People).to receive(:find).with(params[:id]).and_raise(ActiveRecord::RecordNotFound.new(null_object)
    
        put :update, format: :json, .....
        expect(response.body).to error_dailed.to_json
        expect(response.status).to .....
      end
    end
    
    0 讨论(0)
提交回复
热议问题