jeudi 9 avril 2020

rspec - How to test ActiveRecord::RecordNotFound?

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 update
    @people= People.find(params[:id])
    if @people.update(people_params)
      render json: { success: 'Success' }
    else
      render :edit
    end
  rescue ActiveRecord::RecordNotFound => e
    render json: { error: 'Failed') }
  end

And I want to test the situation when the record not found, here's my test for now:

    let(:people) { create(:people) }
    let(:people_id) { people.id }
    let(:user) { people}
    # Other tests...
    context 'when person not found' do
      let(:exception) { ActiveRecord::RecordNotFound }

      # What should I write so that I can let the record not been found?

      before { allow(Person).to receive(:find).and_raise(exception) }

      it 'responds with json containing the error message' do
        expect(JSON.parse(response.body)).to eq({error:'Error'})
      end
    end

I want my test executed under the condition that records not found. But I don't know how to do it. I tried to set let(people) {nil} but it not work. Is there an anyway to do that? Thanks!

Aucun commentaire:

Enregistrer un commentaire