How do I test ajax POST request with RSpec?

风流意气都作罢 提交于 2019-12-19 12:25:17

问题


I just want to test ajax request on controller spec. The product code is below. I'm using Devise for authentication.

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

And spec is below.

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

I expect the response code to be 200, but it returns 401. I guess it must be because the request which rspec throws lacks authenticity_token or something. How can I stub it?

Any help would be greatly appreciated.


回答1:


Answering my own question. I found that format: :json was wrong. Just delete it and it works. Just like below:

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

I'm sorry for all the fuss.




回答2:


I moved format: :json into params hash and it works fine, responding with 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



回答3:


You've probably met CSRF error, try to disable CSRF validation for ajax calls, something like

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


来源:https://stackoverflow.com/questions/11118205/how-do-i-test-ajax-post-request-with-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!