【问题标题】:How do I test for a 204 response in RSpec in Rails?如何在 Rails 的 RSpec 中测试 204 响应?
【发布时间】:2012-03-03 08:02:51
【问题描述】:

我正在测试我的资源控制器的删除操作,如下所示:

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

我希望收到 204/无内容响应。但是,此测试失败,因为服务器返回的响应是 406。当我直接从我的 Rest 测试客户端点击控制器时,响应是 204。

【问题讨论】:

    标签: ruby-on-rails ruby rspec shoulda


    【解决方案1】:

    几年过去了……

    我只想指出,可以使用expect 语法并直接查询状态码。

    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
    

    【讨论】:

      【解决方案2】:

      This 页面显示如何测试响应代码。

      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
      

      【讨论】:

      • 语法没问题。我忘了提到我正在使用should。我想知道在发出删除请求时是否需要设置一些标头。
      • 请发布您的控制器的内容。
      • 注意:至少在 Rails 4 中,response.code 是一个字符串,所以你应该使用response.code.should eql "204"response.response_code.should eql 204。见api.rubyonrails.org/classes/ActionDispatch/Response.html
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      • 2018-07-16
      • 1970-01-01
      • 2012-07-06
      • 1970-01-01
      相关资源
      最近更新 更多