How to do integration testing with RSpec and Devise/CanCan?

前端 未结 6 698
情书的邮戳
情书的邮戳 2020-12-04 08:43

If I have a Devise model User, of which only those users with role :admin are allowed to view a certain url, how can I write an RSpec integration test to check that the stat

6条回答
  •  难免孤独
    2020-12-04 09:49

    As of mid 2017, we have one more, in my opinion better opprotunity to integrate devise in our Rspecs. We are able to utilize stub authentization with helper method sign in defined as described below:

    module ControllerHelpers
        def sign_in(user = double('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
    

    You should also append in spec_helper.rb or rails_helper.rb reference to newly created file:

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

    Then in method just place at the beginning of the method body sign_in for context for authenticated user and you are all set. Up to date details can be found in devise docs here

提交回复
热议问题