How do I test for a 204 response in RSpec in Rails?
Asked Answered
P

2

11

I am testing the delete action of my resource controller as follows:

describe ResourceController do
  context "DELETE destroy" do
    before :each do
      delete :destroy, id: @resource.id
    end
    it { should respond_with(:no_content) }
  end
end

I expect a 204/no-content response. However, this test is failing as the response returned by the server is a 406. The response is a 204 when I hit the controller directly from my Rest test client.

Platt answered 3/3, 2012 at 8:2 Comment(0)
O
9

A couple of years have passed...

I would just like to note that it is possible to use the expect syntax and to query the status code directly.

describe ResourceController do
  context "DELETE destroy" do
    it "should respond with a 204"
      delete :destroy, id: @resource.id
      expect(response).to have_http_status(:no_content)
    end
  end
end
Overalls answered 15/3, 2017 at 8:9 Comment(0)
S
7

This page shows how to test the response code.

describe ResourceController do
  context "DELETE destroy" do
    it "should respond with a 204"
      delete :destroy, id: @resource.id
      response.code.should eql(204)
    end
  end
end
Shopkeeper answered 3/3, 2012 at 11:21 Comment(3)
the syntax is fine. I forgot to mention that I am using shoulda. I wonder if some headers need to be set when making the delete request.Platt
Please post the contents of your controller.Shopkeeper
Note: In Rails 4 at least, response.code is a string, so you should use response.code.should eql "204" or response.response_code.should eql 204. See api.rubyonrails.org/classes/ActionDispatch/Response.htmlErinerina

© 2022 - 2024 — McMap. All rights reserved.