File: integration_helpers.rb

package info (click to toggle)
ruby-devise 4.8.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 752 kB
  • sloc: ruby: 3,877; sh: 24; makefile: 11
file content (63 lines) | stat: -rw-r--r-- 1,733 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# frozen_string_literal: true

module Devise
  # Devise::Test::IntegrationHelpers is a helper module for facilitating
  # authentication on Rails integration tests to bypass the required steps for
  # signin in or signin out a record.
  #
  # Examples
  #
  #  class PostsTest < ActionDispatch::IntegrationTest
  #    include Devise::Test::IntegrationHelpers
  #
  #    test 'authenticated users can see posts' do
  #      sign_in users(:bob)
  #
  #      get '/posts'
  #      assert_response :success
  #    end
  #  end
  module Test
    module IntegrationHelpers
      def self.included(base)
        base.class_eval do
          include Warden::Test::Helpers

          setup :setup_integration_for_devise
          teardown :teardown_integration_for_devise
        end
      end

      # Signs in a specific resource, mimicking a successful sign in
      # operation through +Devise::SessionsController#create+.
      #
      # * +resource+ - The resource that should be authenticated
      # * +scope+    - An optional +Symbol+ with the scope where the resource
      #                should be signed in with.
      def sign_in(resource, scope: nil)
        scope ||= Devise::Mapping.find_scope!(resource)

        login_as(resource, scope: scope)
      end

      # Signs out a specific scope from the session.
      #
      # * +resource_or_scope+ - The resource or scope that should be signed out.
      def sign_out(resource_or_scope)
        scope = Devise::Mapping.find_scope!(resource_or_scope)

        logout scope
      end

      protected

      def setup_integration_for_devise
        Warden.test_mode!
      end

      def teardown_integration_for_devise
        Warden.test_reset!
      end
    end
  end
end