Best way to validate DELETE requests with Rspec?

I started using this way:

  describe "DELETE /v1/categories/{id}" do
   before(:each) do
     #   Login User/Token
   end
   it 'deletes a category' do
     category = Fabricate(:category)
     category2 = Fabricate(:category)

     get "/v1/categories"
     expect(response.status).to eq 200
     expect(JSON.parse(response.body)).to eq([YAML.load(category.to_json),YAML.load(category2.to_json),])

     delete "/v1/categories/#{category.id}"
     expect(response.status).to eq 200

     get "/v1/categories"
     expect(JSON.parse(response.body)).to eq([YAML.load(category2.to_json)])
   end
 end

      

I am not sure what is the best way to test a data delete API request.

+3


source to share


1 answer


So far, your test provides the following:

  • reply to get request before deleting
  • receive request status code
  • delete request response
  • delete request status code
  • response of a receive request after deletion
  • receive request status code

This test covers a lot more than a delete request, but I think it's okay. Better to have tests that don't.



What I need to do to improve this test is to break the routes when testing. I would have 1 test to ensure that the index route works as expected and 1 to ensure that the delete route works. This way, a mistake in the pointing route will not violate your deletion specification. =)

I would have something like this:

describe "GET /v1/categories" do
    before(:each) do
        #   Login User/Token
        category = Fabricate(:category)
        category2 = Fabricate(:category)
        get "/v1/categories"
    end

    it 'should return status 200' do
        expect(response.status).to eq 200
    end

    it 'list all categories' do
        expect(JSON.parse(response.body)).to eq([YAML.load(category.to_json),YAML.load(category2.to_json),])
    end
end

describe "DELETE /v1/categories/:category_id" do
    before(:each) do
        #   Login User/Token
        category = Fabricate(:category)
        category2 = Fabricate(:category)
        delete "/v1/categories/#{category.id}"
    end

    it 'should return status 200' do
        expect(response.status).to eq 200
    end

    it 'should delete the category' do
        expect(Category.all).to eq category2
    end
end

      

+5


source







All Articles