如何使用 RSpec 测试 ajax POST 请求?

编程入门 行业动态 更新时间:2024-10-27 12:37:34
本文介绍了如何使用 RSpec 测试 ajax POST 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我只想在控制器规范上测试 ajax 请求.产品代码如下.我正在使用 Devise 进行身份验证.

I just want to test ajax request on controller spec. The product code is below. I'm using Devise for authentication.

class NotesController < ApplicationController def create if request.xhr? @note = Note.new(params[:note]) if @note.save render json: { notice: "success" } end end end end

规格如下.

describe NotesController do before do user = FactoryGirl.create(:user) user.confirm! sign_in user end it "has a 200 status code" do xhr :post, :create, note: { title: "foo", body: "bar" }, format: :json response.code.should == "200" end end

我希望响应代码是 200,但它返回 401.我想这一定是因为 rspec 抛出的请求缺少真实性_token 或其他东西.我怎样才能存根?

I expect the response code to be 200, but it returns 401. I guess it must be because the request which rspec throws lacks authenticity_token or something. How can I stub it?

任何帮助将不胜感激.

推荐答案

回答我自己的问题.我发现 format: :json 是错误的.只需删除它,它就可以工作.就像下面一样:

Answering my own question. I found that format: :json was wrong. Just delete it and it works. Just like below:

it "has a 200 status code" do xhr :post, :create, note: { title: "foo", body: "bar" } response.code.should == "200" end

我很抱歉让大家大惊小怪.

I'm sorry for all the fuss.

更多推荐

如何使用 RSpec 测试 ajax POST 请求?

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

发布评论

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

>www.elefans.com

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