首页 > 解决方案 > 包含标头的发布操作的 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 密钥,因此需要标头。

非常感谢您对我所缺少的内容的反馈。谢谢

版本:

标签: ruby-on-railsrspec-rails

解决方案


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

解决这个问题的关键是阅读文档并意识到我的格式是错误的。


推荐阅读