【问题标题】:How do I test ajax POST request with RSpec?如何使用 RSpec 测试 ajax POST 请求?
【发布时间】:2012-06-22 12:14:13
【问题描述】:

我只想在控制器规范上测试 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

规格如下。

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抛出的请求缺少authentity_token或其他东西。我该如何存根?

任何帮助将不胜感激。

【问题讨论】:

    标签: ruby-on-rails rspec xmlhttprequest


    【解决方案1】:

    你可能遇到了 CSRF 错误,尝试禁用 ajax 调用的 CSRF 验证,类似

    # In your application_controller.rb
    def verified_request?
      if request.xhr?
        true
      else
        super()
      end
    end
    

    【讨论】:

    • 谢谢。我尝试了这个技巧,但没有任何改变。顺便设置一下csrf verify off,我觉得有点不安。
    • -1 禁用 CSRF 保护并不能解决这个问题。
    【解决方案2】:

    回答我自己的问题。我发现format: :json 是错误的。只需将其删除即可。如下所示:

    it "has a 200 status code" do
      xhr :post, :create, note: { title: "foo", body: "bar" }
      response.code.should == "200"
    end
    

    对于所有的大惊小怪,我很抱歉。

    【讨论】:

    • 我认为这是最优雅的解决方案。当请求是通用 xhr 时,我不喜欢使用 format: json
    • 注意:对于 Rails 5 和更新的 rspec,不推荐使用的形式是:post :create, xhr: true, params: { note: { title: "foo", body: "bar" } }。在未来的版本中,关键字 params 将是必需的,xhr 方法将被删除。
    【解决方案3】:

    我将 format: :json 移到 params 哈希中,它工作正常,响应为 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2017-09-23
      相关资源
      最近更新 更多