ruby-on-rails - 包含标头的发布操作的 RSpec 请求规范导致参数被删除
问题描述
我试图弄清楚为什么我不能在请求规范中同时使用参数和标头。
什么有效:
RSpec.describe Api::V1::UsersController, :type => :request do
before { host! 'api.localhost:3000'}
let(:params) {
{
"user": {
"identifier_for_vendor": "BD43813E"
}
}
}
describe 'Post /users' do
context 'when request is valid' do
before {
post api_users_path,
params: params
}
it "is successful" do
expect(response).to be_successful
end
end
end
end
什么不:
RSpec.describe Api::V1::UsersController, :type => :request do
let(:params) {
{
"user": {
"identifier_for_vendor": "BD43813E"
}
}
}
let(:headers) {
{
"host": "api.localhost:3000",
"Accept": "application/vnd.domain_name.v1",
"Content-Type": "application/vnd.api+json",
"X-API-Key": "fake087uakey"
}
}
describe 'Post /users' do
context 'when request is valid' do
before {
post api_users_path,
params: params,
headers: headers
}
it "successful" do
expect(response).to be_successful
end
end
end
end
以上失败,返回错误:
1) Api::V1::UsersController Post /users when request is valid is successful
Failure/Error: params.require(:user).permit(:identifier_for_vendor)
ActionController::ParameterMissing:
param is missing or the value is empty: user
由于必须确保请求中包含有效的 API 密钥,因此需要标头。
非常感谢您对我所缺少的内容的反馈。谢谢
版本:
- 红宝石版本:2.6.3
- 导轨版本:6.0.3.4
- RSpec 3.10
解决方案
params
所以问题与如何headers
创建对象有关。
参数:
- 我通过了:
{"user": {"identifier_for_vendor": "OFJPJ"} }
- 正确的对象是:
{:params=>{:user=>{:identifier_for_vendor=>"OFJPJ"}}}
标题:
- 我通过了:
{
"host": "api.localhost:3000",
"Accept": "application/vnd.domain_name.v1",
"Content-Type": "application/vnd.api+json",
"X-API-Key": "fake087uakey"
}
- 正确的对象是:
{
"headers" => {
"host" => "api.localhost:3000",
"Accept" => "application/vnd.domain_name.v1",
"X-API-Key" => "api_key"
}
}
最终解决方案如下所示:
RSpec.describe Api::V1::UsersController, :type => :request do
describe 'Post /users' do
context 'when request is valid' do
before do
post api_users_path,
:params => params,
:headers => headers
end
it "is successful" do
expect(response).to be_successful
end
it "returns a data of type user" do
expect(json_data["type"]).to eq("user")
end
end
end
end
解决这个问题的关键是阅读文档并意识到我的格式是错误的。
推荐阅读
- variables - wordpress 中的动态 URL 参数
- wpf - 在类型“GroupBox”中找不到属性“Click”。在网核 3.1
- elasticsearch - 在 Yii2 中为 Elastic 设置索引名称
- spark-java - 在 org.gradle.api.internal.artifacts.dsl 类型的对象上找不到参数 [com.sparkjava:spark-core:2.9.3] 的方法 compile()
- unix - unbale 将邮件发送到带有附件 unix/solaris 10 的分发列表
- python-3.x - 如何制作允许重用密钥的枚举?
- python - Python中的连续UDP查询随机停止
- android - 无法使用多部分请求从颤振应用程序上传图像
- javascript - 为什么 javascript 表单验证中的 required 属性仅适用于我表单中的一个按钮?
- python - 我不明白这行代码是如何工作的