Module: Kernel

Defined in:
lib/kernel.rb

Overview

Extension of the global Kernel module to provide the Fix method. This module provides a global entry point to the Fix testing framework, allowing specifications to be defined and managed from anywhere in the application.

The Fix method can be used in two main ways:

  1. Creating named specifications for reuse

  2. Creating anonymous specifications for immediate testing

Instance Method Summary collapse

Instance Method Details

#Fix(name = nil) { ... } ⇒ Fix::Set

Defines a new test specification or creates an anonymous specification set. When a name is provided, the specification is registered globally and can be referenced later using Fix. Anonymous specifications are executed immediately and cannot be referenced later.

Specifications can use three levels of requirements, following RFC 2119:

  • MUST/MUST_NOT: Absolute requirements or prohibitions

  • SHOULD/SHOULD_NOT: Strong recommendations that can be ignored with good reason

  • MAY: Optional features that can be implemented or not

Available matchers include:

  • Basic Comparison: eq(expected), eql(expected), be(expected), equal(expected)

  • Type Checking: be_an_instance_of(class), be_a_kind_of(class)

  • State & Changes: change(object, method).by(n), by_at_least(n), by_at_most(n),

    from(old).to(new), to(new)
    
  • Value Testing: be_within(delta).of(value), match(regex),

    satisfy { |value| ... }
    
  • Exceptions: raise_exception(class)

  • State Testing: be_true, be_false, be_nil

  • Predicate Matchers: be_* (e.g., be_empty), have_* (e.g., have_key)

Examples:

Creating a named specification with multiple contexts and matchers

Fix :Calculator do
  on(:add, 2, 3) do
    it MUST eq 5
    it MUST be_an_instance_of(Integer)
  end

  with precision: :high do
    on(:divide, 10, 3) do
      it MUST be_within(0.001).of(3.333)
    end
  end

  on(:divide, 1, 0) do
    it MUST raise_exception ZeroDivisionError
  end
end

Creating and immediately testing an anonymous specification

Fix do
  it MUST be_positive
  it SHOULD be_even
  it MAY be_prime
end.test { 42 }

Testing state changes

Fix :Account do
  on(:deposit, 100) do
    it MUST change(, :balance).by(100)
    it SHOULD change(, :updated_at)
  end

  on(:withdraw, 50) do
    it MUST change(, :balance).by(-50)
    it MUST_NOT change(, :status)
  end
end

Using predicates and custom matchers

Fix :Collection do
  with items: [] do
    it MUST be_empty
    it MUST_NOT have_errors
    it SHOULD satisfy { |c| c.valid? && c.initialized? }
  end
end

Parameters:

  • name (Symbol, nil) (defaults to: nil)

    Optional name to register the specification under

Yields:

  • Block containing the specification definition using Fix DSL

Returns:

  • (Fix::Set)

    A specification set ready for testing

Raises:

See Also:



98
99
100
# File 'lib/kernel.rb', line 98

def Fix(name = nil, &block)
  ::Fix.spec(name, &block)
end