SusSourceSusExpect

class Expect

Represents an expectation that can be used with predicates to make assertions.

Definitions

def initialize(assertions, subject, inverted: false, distinct: false)

Initialize a new Expect instance.

Signature

parameter assertions Assertions

The assertions instance to use.

parameter subject Object

The subject to make expectations about.

parameter inverted Boolean

Whether the expectation is inverted (not).

parameter distinct Boolean

Whether this expectation should be treated as distinct.

Implementation

def initialize(assertions, subject, inverted: false, distinct: false)
	@assertions = assertions
	@subject = subject
	
	# We capture this here, as changes to state may cause the inspect output to change, affecting the output produced by #print. The representation is buffered (as a stream of styled tokens) and truncated to avoid excessively noisy output for large subjects; colours are resolved later when the buffer is replayed into the output.
	@inspect = Output::Variable.buffer(@subject)
	
	@inverted = inverted
	@distinct = true
end

attr :subject

Signature

attribute Object

The subject being tested.

attr :inverted

Signature

attribute Boolean

Whether the expectation is inverted.

def not

Invert this expectation (expect not).

Signature

returns Expect

A new Expect instance with inverted expectation.

Implementation

def not
	self.dup.tap do |expect|
		expect.instance_variable_set(:@inverted, !@inverted)
	end
end

def print(output)

Print a representation of this expectation.

Signature

parameter output Output

The output target.

Implementation

def print(output)
	output.write("expect ")
	output.append(@inspect)
	output.write(" ")
	
	if @inverted
		output.write("not to", :reset)
	else
		output.write("to", :reset)
	end
end

def to(predicate)

Apply a predicate to this expectation.

Signature

parameter predicate Object

The predicate to apply.

returns Expect

Returns self for method chaining.

Implementation

def to(predicate)
	# This gets the identity scoped to the current call stack, which ensures that any failures are logged at this point in the code.
	identity = @assertions.identity&.scoped
	
	@assertions.nested(self, inverted: @inverted, identity: identity, distinct: @distinct) do |assertions|
		predicate.call(assertions, @subject)
	end
	
	return self
end

def and(predicate)

Apply another predicate to this expectation (alias for #to).

Signature

parameter predicate Object

The predicate to apply.

returns Expect

Returns self for method chaining.

Implementation

def and(predicate)
	return to(predicate)
end