Warm tip: This article is reproduced from stackoverflow.com, please click
ruby-on-rails rspec

rspec sign_in works in requests but not in controller

发布于 2020-04-03 23:37:40

I have this spec\requests\sessions_spec.rb

require 'rails_helper'

RSpec.describe "Sessions" do
 it "signs user in and out" do
    u = sign_in mockuser
    p u.inspect 
 end

end

the above code works well,

but when I call the same sign_in from controller it doesn't, I am fighting this for 10 hours now.

spec\controllers\properties_controller_spec.rb

require 'rails_helper'

describe PropertiesController do

    context 'when searching after  login' do 
        it 'should success and render to index page' do
           u = sign_in mockuser
           p u.inspect // returns nil
        end
    end
end

my spec\support\devise_request_spec_helper.rb

module DeviseRequestSpecHelpers

   include Warden::Test::Helpers

   def sign_in(resource_or_scope, resource = nil)
     resource ||= resource_or_scope
     scope = Devise::Mapping.find_scope!(resource_or_scope)
     login_as(resource, scope: scope)
   end
end
Questioner
Code Tree
Viewed
93
max 2020-01-31 20:30

The Warden test helpers don't work for controller specs since controller specs fake the entire request phase and thus bypass the middleware.

Either use Devise::Test::ControllerHelpers which stubs out warden or get with the program and ditch controller specs and just write request specs instead.

Request specs provide a high-level alternative to controller specs. In fact, as of RSpec 3.5, both the Rails and RSpec teams discourage directly testing controllers in favor of functional tests like request specs.
- rspec-rails readme