Best way to test DELETE requests with Rspec?

Ivan Santos picture Ivan Santos · Oct 12, 2014 · Viewed 12.3k times · Source

I started using that 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'm not sure if is the best way to test an API Request to delete data.

Answer

Paulo Henrique picture Paulo Henrique · Oct 12, 2014

So far your test are ensuring this:

  • the response of the get request before deleting
  • the status code of the get request
  • the response of the delete request
  • the status code of the delete request
  • the response of the get request after deleting
  • the status code of the get request

This test is covering a lot more then the delete request but i think it is fine. Its better to have this kind of tests then having none.

What i wold do to improve this test would be to split the routes when testing. I would have 1 test to ensure the index route is working as expected and 1 test to make sure the delete route is working. This way a bug on the index route won't break your delete spec. =)

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