How do I simulate a login with RSpec?

前端 未结 4 1804
悲哀的现实
悲哀的现实 2020-12-08 02:27

I have been playing with Rails for a couple of years now and have produced a couple of passable apps that are in production. I\'ve always avoided doing any testing though an

4条回答
  •  误落风尘
    2020-12-08 03:08

    Add helper file in spec/support/controller_helpers.rb and copy content below

    module ControllerHelpers
        def sign_in(user)
          if user.nil?
            allow(request.env['warden']).to receive(:authenticate!).and_throw(:warden, {:scope => :user})
            allow(controller).to receive(:current_user).and_return(nil)
          else
            allow(request.env['warden']).to receive(:authenticate!).and_return(user)
            allow(controller).to receive(:current_user).and_return(user)
          end
        end
      end
    

    Now add following lines in spec/rails_helper.rb or spec/spec_helper.rb file

    require 'support/controller_helpers'
    
    RSpec.configure do |config|
    
        config.include Devise::TestHelpers, :type => :controller
        config.include ControllerHelpers, :type => :controller
    
      end
    

    Now in your controller spec file.

    describe  "GET #index" do
    
        before :each do        
            @user=create(:user)
            sign_in @user
        end
          ...
    end
    

    Devise Official Link

提交回复
热议问题