module Authpwn::TestExtensions

Included in all test cases.

Public Instance Methods

with_blocked_credential(blocked_credential, reason = :blocked) { || ... } click to toggle source

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.

# 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