Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec, authenticating Devise user in request specs

I'm trying to write RSpec request specs in order to test my service API and for that I need the user to be authenticated. I found some examples on the net but nothing works, for the moment I'm stuck with this:

require "spec_helper"

include Warden::Test::Helpers
Warden.test_mode!

describe "My requests" do

  it "creates an imaginary object" do
    user = FactoryGirl.create(:user)
    login_as(user, :scope => :user)
    post "/my_service", :my_data=> {:some => "data"}
    expect(response.body).to include("success")
  end

end

And the error I'm getting is:

 ArgumentError: uncaught throw :warden

Thank you for your help.

like image 816
a.s.t.r.o Avatar asked Mar 04 '13 21:03

a.s.t.r.o


2 Answers

It is simplest to just:

spec/rails_helper.rb

RSpec.configure do |config|
  # ...
  config.include Devise::Test::IntegrationHelpers, type: :request
end

And just use sign_in in your request spec. This is the equivalent of declaring include Devise::Test::IntegrationHelpers in an system/feature spec or Rails system/controller test.

Doing it this way leads to a 'better' test.

like image 58
ybakos Avatar answered Oct 23 '22 19:10

ybakos


You need to actually sign in the user (i.e. the user needs to submit the login form, or at least do a POST on your login action) as explained here: Stubbing authentication in request spec

like image 38
doesterr Avatar answered Oct 23 '22 20:10

doesterr