Module: Authpwn::TestExtensions

Included in:
ActiveSupport::TestCase
Defined in:
lib/authpwn_rails/test_extensions.rb

Overview

Included in all test cases.

Instance Method Summary collapse

Instance Method Details

#with_blocked_credential(blocked_credential, reason = :blocked, &block) ⇒ Object

Stubs User#auth_bounce_reason to block a given credential.

The default implementation of User#auth_bounce_reason always returns nil. Your application’s implementation might differ. Either way, the method is replaced for the duration of the block, such that it returns :block if the credential matches the given argument, and nil otherwise.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/authpwn_rails/test_extensions.rb', line 12

def with_blocked_credential(blocked_credential, reason = :blocked, &block)
  # Stub a method in all User instances for this test only.
  # mocha.any_instance doesn't work because ActiveRecord doesn't use new
  # to instantiate records.
  ::User.class_eval do
    alias_method :_auth_bounce_reason_wbc_stub, :auth_bounce_reason
    define_method :auth_bounce_reason do |credential|
      credential == blocked_credential ? reason : nil
    end
  end

  begin
    yield
  ensure
    ::User.class_eval do
      undef_method :auth_bounce_reason
      alias_method :auth_bounce_reason, :_auth_bounce_reason_wbc_stub
      undef_method :_auth_bounce_reason_wbc_stub
    end
  end
end