【问题标题】:Rails, how to test 400 response with missing parameterRails,如何测试缺少参数的 400 响应
【发布时间】:2015-12-09 18:48:41
【问题描述】:

我正在使用 Rails 4.2.5,我正在尝试测试来自控制器的预期 400 响应,以防出现格式错误的请求。参数验证逻辑由strong_parameters处理。

上下文

在我的控制器中,我有:

def user_params
  params.require(:user).permit(:foo, :bar, :baz)
end

我在 POST 请求中引用 user_params,并将 AcceptContentType 标头设置为 application/json

development 中,不带user 参数的POST 将引发ActionController::ParameterMissing 异常。
如果我在我的environments/development.rb 文件中设置它:

Rails.application.configure do
  config.consider_all_requests_local = false
end

Rails 将像 production 一样运行,并返回简单的 400 响应而不是调试页面。太好了。

问题

不过,我在控制器测试中做同样的事情时遇到了麻烦 (rspec-rails ~> 3.4)。

具体来说,这将通过:

expect {
  post :action, malformed_params
}.to raise_error(ActionController::ParameterMissing)

但这不会因为引发异常:

post :action, malformed_params
expect(response.status).to eql 400

我已经尝试将consider_all_requests_local翻转为测试环境,无济于事。

有什么解决办法吗? 这上面有an old answer,但它没有帮助(甚至提问者也承认它没有用)。

编辑:

根据 cmets 的要求,以下是控制器规范中的参数:

let(:user_data) do
  { foo: "foo", bar: "bar", baz: "baz" }
end

let(:good_params) do
  {
    some_id: SecureRandom.uuid,
    user: user_data
  }
end

let(:malformed_params) do
  { some_id: SecureRandom.uuid }.merge(user_data)
end

let(:incomplete_params) do
  { some_id: SecureRandom.uuid }
end

good_params 适用于幸福的道路。当我想测试 400 时,malformed_paramsincomplete_params 都不起作用:两者都会引发异常并导致测试失败。

我已经验证,当 POST 到正在运行的服务器时,相同的参数负载也可以工作(在 development 中,但如上所述调整了配置)。

【问题讨论】:

标签: ruby-on-rails ruby rspec strong-parameters


【解决方案1】:

如果您想在所有环境中模拟生产并在缺少任何必需参数时始终提高 400,而不是更改每个配置文件,您可以放入您的控制器(或 ApplicationController 或任何其他 mixin 以使其更多一般):

# assuming we're talking about a JSON API

rescue_from ActionController::ParameterMissing do |e|
  render json: { error: e.message }, status: :bad_request
end

# or more general for any kind of response

rescue_from ActionController::ParameterMissing do |e|
  head :bad_request
end

【讨论】:

    【解决方案2】:

    引发的异常是正确的,因为没有发送格式错误的 json。 有效载荷格式正确,但缺少参数。

    你必须尝试类似的东西:

    '{ i am malformed json'
    

    【讨论】:

    • 不,我不是要验证 JSON 语法结构。如果缺少参数,我正在尝试检查响应,并且响应应该是 400,而不是异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多