Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test ajax POST request with RSpec?

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.

like image 496
morygonzalez Avatar asked Jun 20 '12 11:06

morygonzalez


1 Answers

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.

like image 190
morygonzalez Avatar answered Sep 19 '22 23:09

morygonzalez