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

mor*_*lez 19 rspec ruby-on-rails xmlhttprequest

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

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

规格如下.

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
Run Code Online (Sandbox Code Playgroud)

我希望响应代码为200,但它返回401.我想这肯定是因为rspec抛出的请求缺少authenticity_token或其他东西.我该如何存根?

任何帮助将不胜感激.

mor*_*lez 36

回答我自己的问题.我发现那format: :json是错的.只需删除它就可以了.如下所示:

it "has a 200 status code" do
  xhr :post, :create, note: { title: "foo", body: "bar" }
  response.code.should == "200"
end
Run Code Online (Sandbox Code Playgroud)

我很抱歉所有的大惊小怪.

  • 注意:使用Rails 5和更新的rspec,不推荐使用的形式是:`post:create,xhr:true,params:{note:{title:"foo",body:"bar"}}`.在将来的版本中,将需要关键字params并删除`xhr`方法. (14认同)

dim*_*uch -4

您可能遇到过 CSRF 错误,尝试禁用 ajax 调用的 CSRF 验证,例如

# In your application_controller.rb
def verified_request?
  if request.xhr?
    true
  else
    super()
  end
end
Run Code Online (Sandbox Code Playgroud)

  • -1 禁用 CSRF 保护并不能解决此问题。 (11认同)