Rails 强参数 - 无需密钥即可允许请求

cov*_*ise 1 rspec ruby-on-rails strong-parameters

我正在开发 Rails API,并在控制器中使用强参数。我的请求规范对于一种型号失败,但适用于所有其他型号。每个型号的控制器几乎都是相同的。

正如您在下面的规范中看到的,请求正文应该是{ "tag": { "name": "a good name" }}. 然而,这个规范使用的{ "name": "a good name" }应该是无效的,因为它缺少“标签”键。相同控制器功能的相同规格适用于许多其他型号。

另一个有趣的变化是,如果我更改控制器的强参数,params.require(:not_tag).permit(:name)它会因不包含“not_tag”键而引发错误。

  • 红宝石:2.6.5p114
  • 轨道:6.0.1
  • 预期响应状态:422
  • 收到响应状态:201

控制器

class TagsController < ApplicationController
  before_action :set_tag, only: [:show, :update, :destroy]

  # Other methods...

  # POST /tags
  def create
    @tag = Tag.new(tag_params)

    if @tag.save
      render "tags/show", status: :created
    else
      render json: @tag.errors, status: :unprocessable_entity
    end
  end

  # Other methods...

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_tag
      @tag = Tag.find_by(id: params[:id])
      if !@tag
        object_not_found
      end
    end

    # Only allow a trusted parameter "white list" through.
    def tag_params
      params.require(:tag).permit(:name)
    end

    # render response for objects that aren't found
    def object_not_found
      render :json => {:error => "404 not found"}.to_json, status: :not_found
    end
end
Run Code Online (Sandbox Code Playgroud)

请求规格

require 'rails_helper'
include AuthHelper
include Requests::JsonHelpers

RSpec.describe "Tags", type: :request do
  before(:context) do
    @user = create(:admin)
    @headers = AuthHelper.authenticated_header(@user)
  end

  # A bunch of other specs...

  describe "POST /api/tags" do
    context "while authenticated" do
      it "fails to create a tag from malformed body with 422 status" do
        malformed_body = { "name": "malformed" }.to_json
        post "/api/tags", params: malformed_body, headers: @headers
        expect(response).to have_http_status(422)
        expect(Tag.all.length).to eq 0
      end
    end
  end

# A bunch of other specs...

  after(:context) do
    @user.destroy
    @headers = nil
  end
end
Run Code Online (Sandbox Code Playgroud)

Anu*_*wal 5

此行为是因为Rails 6 中默认启用的ParamsWrapperwrap_parameters功能将接收到的参数包装到嵌套散列中。因此,这允许客户端发送请求而无需在根元素中嵌套数据。

例如,在名为 的模型中Tag,它基本上转换

{
  name: "Some name",
  age: "Some age"
}
Run Code Online (Sandbox Code Playgroud)

{
  tag:
    {
      name: "Some name",
      age: "Some age"
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,正如您在测试中看到的那样,如果将所需的密钥更改为not_tag,则包装会按照预期中断 API 调用。

可以使用该文件更改此配置config/initializers/wrap_parameters.rb。在该文件中,您可以设置wrap_parameters format: [:json]wrap_parameters format: []禁止此类参数包装。