本文介绍了如何使用 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 请求?
发布评论