【问题标题】:Can't use rails http status on grape exception?不能在葡萄异常上使用 Rails http 状态?
【发布时间】:2019-04-11 20:38:48
【问题描述】:

我是 Rails 编程的新手,我在引发葡萄异常时尝试使用 rails status code,但我的测试失败了。我在葡萄文档中找不到任何示例,所以这可能是不可能的。

我想知道有没有可能,如果没有,为什么会这样?

这行得通:

rescue_from Example::IsExampleWorking do |_e|
    error!({ messages: ["Example is not working because it was not found"] }, 404)
end

但这不是:

rescue_from Example::IsExampleWorking do |_e|
    error!({ messages: ["Example is not working because it was not found"] }, :not_found)
end

我的测试是:

it "return a 404 Not Found status" do
  expect(response).to have_http_status(:not_found)
end

编辑:伙计们,我忘了提到他测试的错误信息是

undefined method `to_i' for :not_acceptable:Symbol
Did you mean?  to_s

但我没有找到有关葡萄文档的任何文档,以确保它们仅接受整数作为第二个参数。

谢谢你:)

【问题讨论】:

  • 嗨,欢迎来到 SO。您能否也发布您正在测试的代码。
  • 是的。你可能会用这个问题在葡萄回购中创建一个问题。解决方案之一是使用Rack::Utils::SYMBOL_TO_STATUS_CODE[:not_found]。在这种情况下,我更喜欢一个数字:)

标签: ruby-on-rails grape


【解决方案1】:

Grape 允许在定义参数时指定type

params do
  # Basic usage: require a parameter of a certain type
  requires :param_name, type: Integer
end

见:https://www.rubydoc.info/github/ruby-grape/grape/Grape%2FDSL%2FParameters:requires

【讨论】:

    【解决方案2】:

    Http 状态码总是只有整数。那是行业标准。您不能更改 http 状态代码或将 http 状态代码作为字符串发送。

    在此处查找 http 状态代码列表。 https://www.restapitutorial.com/httpstatuscodes.html

    这并不特定于 rails 或 grape 或任何其他框架。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多