为 RSpec 和 Rails

编程入门 行业动态 更新时间:2024-10-07 04:26:40
本文介绍了为 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"

wrap_parameters 似乎以这种方式声明

wrap_parameters seems to be working declared this way

wrap_parameters User, format: :json

用于User模型

更多推荐

为 RSpec 和 Rails

本文发布于:2023-11-25 06:20:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628650.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:RSpec   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!