如何使用RSpec测试ajax POST请求?
我只是想在控制器规范上测试ajax请求。 产品代码如下。 我正在使用Devise进行身份validation。
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抛出的请求缺少authenticity_token或其他东西。 我该如何存根?
任何帮助将不胜感激。
回答我自己的问题。 我发现format: :json
错了。 只需删除它就可以了。 如下所示:
it "has a 200 status code" do xhr :post, :create, note: { title: "foo", body: "bar" } response.code.should == "200" end
我很抱歉所有的大惊小怪。
我将格式:: json移动到params hash并且工作正常,用json响应。
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
您可能遇到过CSRF错误,尝试禁用ajax调用的CSRFvalidation,例如
# In your application_controller.rb def verified_request? if request.xhr? true else super() end end