我正在使用Rails API,并且在控制器中使用了强大的参数。我有一个请求规范,该规范对于一个模型失败,但在所有其他模型上都有效。每个模型的控制器几乎都相同。
如您在下面的规范中所见,请求正文应为{ "tag": { "name": "a good name" }}
。但是,此规范使用的{ "name": "a good name" }
应该无效,因为它缺少“标记”键。具有相同控制器功能的相同规格适用于许多其他型号。
另一个有趣的变化是,如果我将控制器的strong参数更改为params.require(:not_tag).permit(:name)
,则会因为不包含“ not_tag”键而引发错误。
控制器
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
请求规范
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
此行为是由于在Rails 6中默认启用了ParamsWrapper功能。wrap_parameters
将收到的参数包装到嵌套的哈希中。因此,这允许客户端发送请求而无需在根元素中嵌套数据。
例如,在名为Tag
的模型中,它基本上会进行转换
{
name: "Some name",
age: "Some age"
}
to
{
tag:
{
name: "Some name",
age: "Some age"
}
}
但是,如您在测试中所见,如果将所需的密钥更改为not_tag
,则包装将按预期中断API调用。
可以使用config/initializers/wrap_parameters.rb
文件更改此配置。在该文件中,可以将wrap_parameters format: [:json]
设置为wrap_parameters format: []
以禁止这种参数包装。