Module: SwitchUser::RSpecFeatureHelpers

Defined in:
lib/switch_user/rspec/feature_helpers.rb

Defined Under Namespace

Classes: InvalidArgument

Instance Method Summary collapse

Instance Method Details

#switch_user(user_record_or_scope, user_id = nil) ⇒ Object



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
# File 'lib/switch_user/rspec/feature_helpers.rb', line 7

def switch_user(user_record_or_scope, user_id = nil)
  _user_scope =
    case user_record_or_scope
    when ActiveRecord::Base
      user_record_or_scope.model_name.singular
    else
      user_record_or_scope
    end

  _user_scope = _user_scope.to_s

  raise SwitchUser::InvalidScope,
        "don't allow this user sign in, please check config.available_users" unless SwitchUser.available_scopes
    .include?(_user_scope) || SwitchUser.available_scopes.include?(_user_scope.to_sym)

  _user_id =
    case user_record_or_scope
    when ActiveRecord::Base
      identifier =
        SwitchUser.available_users_identifiers[_user_scope] ||
          SwitchUser.available_users_identifiers[_user_scope.to_sym]
      raise SwitchUser::InvalidScope,
            "don't allow switch this user, please check config.available_users_identifiers" if identifier.nil?

      user_record_or_scope.send identifier
    else
      user_id
    end

  raise InvalidArgument, "don't allow switch this user, user_id is empty" if _user_id.to_s.empty?

  scope_identifier = "#{_user_scope}_#{_user_id}"

  visit "/switch_user?scope_identifier=#{scope_identifier}"
end