为 RSpec 和 Rails-API 设置 Content-Type 标头 [英] Setting Content-Type header for RSpec and Rails-API

查看:57
本文介绍了为 RSpec 和 Rails-API 设置 Content-Type 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 rails-api gem 来构建 Web 服务并且想要使用 RSpec 测试我的 API.我发出的每个请求,无论 HTTP 方法如何,都将 CONTENT_TYPE 标头设置为application/x-www-form-urlencoded".这不是真正的问题,直到我尝试使用 wrap_parameters 在我的控制器中,它对 params 哈希没有任何影响:

I'm using the rails-api gem to build a web service and want to test my API with RSpec. Every request I make, regardless of the HTTP method has the CONTENT_TYPE header set as "application/x-www-form-urlencoded". This isn't really a problem until I try to use wrap_parameters in my controller and it's not have any affect on the params hash:

class ApplicationController < ActionController::API
  include ActionController::ParamsWrapper
end

class ProjectsController < ApplicationController
  wrap_parameters :project, include: [:name]
  # ...
end

此 hack 不再有效(@request 为零),并且没有我找到的其他 Stack Overflow 帖子也是如此.

This hack no longer works (@request is nil), and none of the other Stack Overflow posts I found work either.

如果我在 RSpec 测试中提出以下请求:

If I make the following request in my RSpec test:

put "/projects/1.json", {name: 'Updated Project 1'}

并在我的控制器中放置一个调试器,我得到:

and put a debugger in my controller I get:

(rdb:1) p params
    { "name"=>"Updated Project 1",
  "action"=>"update",
  "controller"=>"projects",
  "id"=>"5539bbd9-010c-4cfb-88d3-82dadbc99507",
  "format"=>"json"
}

(rdb:1) p request.content_type
"application/x-www-form-urlencoded"

我希望在 params 散列中看到类似这样的内容(注意添加了项目键):

I'm expecting to see something like this for the params hash (note the addition of the project key):

{ "name"=>"Updated Project 1",
  "action"=>"update",
  "controller"=>"projects",
  "id"=>"5539bbd9-010c-4cfb-88d3-82dadbc99507",
  "format"=>"json",
  "project" => {"name" => "Updated Project 1"}
}

是否可以仅使用 RSpec 设置内容类型标头?还是我必须使用机架/测试才能实现此功能?

推荐答案

很多挫折和变化,这对我有用.Rails 3.2.12 Rspec 2.10

A lot of frustration and variations and that's what worked for me. Rails 3.2.12 Rspec 2.10

 @request.env["HTTP_ACCEPT"] = "application/json"
 @request.env["CONTENT_TYPE"] = "application/json"
 put :update, :id => 1, "email" => "bing@test.com"

wrap_parameters 似乎以这种方式声明

wrap_parameters seems to be working declared this way

wrap_parameters User, format: :json

用于User模型

这篇关于为 RSpec 和 Rails-API 设置 Content-Type 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆