如何使用 RSpec 测试 ajax POST 请求? [英] How do I test ajax POST request with RSpec?
本文介绍了如何使用 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 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文