ruby-on-rails - 如何使用 RSpec 测试 ajax POST 请求?

标签 ruby-on-rails rspec xmlhttprequest

我只想在 Controller 规范上测试 ajax 请求。产品代码如下。我正在使用设计进行身份验证。

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 或其他东西。我该如何 stub ?

任何帮助将不胜感激。

最佳答案

回答我自己的问题。我发现 format: :json错了。只需将其删除即可。就像下面这样:

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

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

关于ruby-on-rails - 如何使用 RSpec 测试 ajax POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11118205/

相关文章:

ruby-on-rails - has_secure_password、RSpec 和用户创建

ruby-on-rails - 如何加快为 rspec 测试创建 5,000 条记录的速度?

javascript - IE 中的 Ajax 异步 - 错误 "The Data Necessary to Complete This Operation is Not Yet Available"

ruby-on-rails - 如何使用accepts_nested_attributes_for创建嵌套对象

ruby-on-rails - 在 Rails 中使用隐藏字段的替代方法。保证安全

javascript - 每次提交时数据库条目数都会增加一倍

ruby-on-rails-3 - rspec Controller 空 session

javascript - 如何使用 POST 和 XMLHttpRequest 将 JPEG 文件发送到服务器?

javascript - window.XMLHttpRequest 的含义? ( Ajax )

ruby-on-rails - 按日期范围生成报告