SusSourceSusMocks

module Mocks

Provides mock management functionality for test cases.

Definitions

def after(error = nil)

Clean up all mocks after the test completes.

Signature

parameter error Exception | Nil

The error that occurred, if any.

Implementation

def after(error = nil)
	super
	
	@mocks&.each_value(&:clear)
end

def mock(target)

Create or access a mock for the given target.

Signature

parameter target Object

The object to mock.

yields {|mock| ...}

Optional block to configure the mock.

returns Mock

The mock instance for the target.

Implementation

def mock(target)
	validate_mock!(target)
	
	mock = self.mocks[target]
	
	if block_given?
		yield mock
	end
	
	return mock
end

MockTargetError = Class.new(StandardError)

Error raised when attempting to mock a frozen object.

def validate_mock!(target)

Validate that the target can be mocked.

Signature

parameter target Object

The object to validate.

raises MockTargetError

If the target is frozen.

Implementation

def validate_mock!(target)
	if target.frozen?
		raise MockTargetError, "Cannot mock frozen object #{target.inspect}!"
	end
end

def mocks

Get the mocks hash, creating it if necessary.

Signature

returns Hash

A hash mapping targets to their mock instances.

Implementation

def mocks
	@mocks ||= Hash.new{|h,k| h[k] = Mock.new(k)}.compare_by_identity
end