我只想在 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/