小编mor*_*lez的帖子

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

我只是想在控制器规范上测试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或其他东西.我该如何存根?

任何帮助将不胜感激.

rspec ruby-on-rails xmlhttprequest

19
推荐指数
2
解决办法
2万
查看次数

标签 统计

rspec ×1

ruby-on-rails ×1

xmlhttprequest ×1