spectus 5.0.2 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 27755e146e515eb8767ab7d71d9e5f712538376e89df1100f6629ba27f5635c2
4
- data.tar.gz: 5e9c7e45e5f91f5a98aa62ea005732fec936c2dd456a8c52d9d50e55b81510ec
3
+ metadata.gz: 92e8a3d87559a6f4c65aba5de5bb1a4430a97643a575fdf6bfae472089c3d735
4
+ data.tar.gz: f6e072160332e5f43b49e90030a2ab285f91ce5a3d62787212a795de41e28919
5
5
  SHA512:
6
- metadata.gz: 885d638883c196a7511d2402c4113c44b4d1f9dcca8784dfdbd1bd7061c32da8fbfbf50c001d0e5c6c1320fef1dabdaa320643d760651067a1441cde0acfcd69
7
- data.tar.gz: 202bef0668a0477517d5cfce46428b7c34f376dc5033018427533e8c3d6bdf1263ae816c96f50ef65ec6d093a3cc4654c0baa75345fcb7ccf5ca9ff6343ea33c
6
+ metadata.gz: 538a2ad991c57d8e5c93abc35985a2e0eef3e1dcee66cc80e73e31a7916f7aa33d1fcecfc6d5ed4ecbd2bb54948d5e1f5df25222a27b5a9492518df16c67513f
7
+ data.tar.gz: 053e1923192a01dd17eb3fd5fe4b34b810d8b2f66891fc74d09d5e4c5d7483604b591f6302a204e2a0d556c4b71c54a4fb1a253818409a897f0070ac7d56c3d4
data/LICENSE.md CHANGED
@@ -1,6 +1,6 @@
1
1
  The MIT License (MIT)
2
2
 
3
- Copyright (c) 2014-2025 Cyril Kato
3
+ Copyright (c) 2014-2026 Cyril Kato
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
data/README.md CHANGED
@@ -4,141 +4,96 @@
4
4
  [![Yard documentation](https://img.shields.io/badge/Yard-documentation-blue.svg?logo=github)](https://rubydoc.info/github/fixrb/spectus/main)
5
5
  [![License](https://img.shields.io/github/license/fixrb/spectus?label=License&logo=github)](https://github.com/fixrb/spectus/raw/main/LICENSE.md)
6
6
 
7
- > A Ruby testing library that brings precision to your expectations using RFC 2119 compliance levels. 🚥
8
-
9
- ## Quick Start
10
-
11
- ```ruby
12
- require "spectus"
13
- require "matchi"
14
-
15
- # Define a must-have requirement
16
- test = Spectus.must Matchi::Eq.new(42)
17
- test.call { 42 } # => Pass ✅
18
-
19
- # Define an optional feature
20
- test = Spectus.may Matchi::Be.new(:empty?)
21
- test.call { [].empty? } # => Pass ✅
22
- ```
7
+ Spectus expresses expectations with the requirement levels of [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119): what a value MUST do, SHOULD do, or MAY do. An expectation is a level, a negation and a matcher; called with a block, it gives a result that says how it went, and never raises for an expectation that is not met.
23
8
 
24
9
  ## Installation
25
10
 
26
- Add to your Gemfile:
27
-
28
11
  ```ruby
12
+ # Gemfile
29
13
  gem "spectus"
30
- gem "matchi" # For matchers
31
- ```
32
-
33
- Or install directly:
34
-
35
- ```bash
36
- gem install spectus
37
- gem install matchi
14
+ gem "matchi" # the matchers of Fix, or any object with match? and to_s
38
15
  ```
39
16
 
40
- ## Understanding RFC 2119
17
+ Spectus requires Ruby 3.3 or later, and depends on [Defi](https://github.com/fixrb/defi).
41
18
 
42
- Spectus implements [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt) requirement levels to bring clarity and precision to test expectations:
19
+ ## Usage
43
20
 
44
- - **MUST** (✅): Absolute requirement, no exceptions
45
- - **SHOULD** (⚠️): Strong recommendation with valid exceptions
46
- - **MAY** (💡): Optional feature
21
+ ```ruby
22
+ require "spectus"
23
+ require "matchi"
47
24
 
48
- This approach helps you clearly communicate the importance of each test in your suite.
25
+ requirement = Spectus.must(Matchi::Eq.new(42))
26
+ result = requirement.call { 6 * 7 }
27
+ result.passed? # => true
28
+ result.outcome # => :success
29
+ result.to_s # => "Success: expected 42 to eq 42"
49
30
 
50
- ## Features
31
+ Spectus.must_not(Matchi::Eq.new(42)).call { 42 }.to_s # => "Failure: expected 42 not to eq 42"
32
+ Spectus.should(Matchi::Be.new(3)).call { 2 }.to_s # => "Warning: expected 2 to be 3"
33
+ Spectus.may(Matchi::Predicate.new(:be_foo)).call { 42 }.outcome # => :info
34
+ Spectus.must(Matchi::Eq.new(42)).call { 1 / 0 }.to_s # => "Error: ZeroDivisionError: divided by 0"
35
+ ```
51
36
 
52
- ### Requirement Levels
37
+ `Spectus.must`, `must_not`, `should`, `should_not` and `may` build a `Spectus::Requirement`; `may` has no negative form, the RFC having none. A requirement is `Data`: its `level` (`:MUST`, `:SHOULD` or `:MAY`), its `negate` and its `matcher`, which is any object with a `match?` method that takes the block and answers `true` or `false`, and a `to_s` that describes it. The matcher is neither copied nor frozen. The five functions are the normal entry; `Spectus::Requirement.new(level:, negate:, matcher:)` is the general one.
53
38
 
54
- | Level | Description | Pass Conditions |
55
- |-------|-------------|-----------------|
56
- | MUST | Absolute requirement | Only when exact match |
57
- | SHOULD | Recommended behavior | When matches or has valid reason not to |
58
- | MAY | Optional feature | When matches or not implemented |
39
+ ## Outcomes
59
40
 
60
- ### Results Classification
41
+ Two questions tell the levels apart. Does the method exist? MUST and SHOULD require it, MAY does not. Does it do what is specified? MUST and MAY require it, SHOULD recommends it. Hence five outcomes:
61
42
 
62
- - **Pass Results:**
63
- - ✅ Success (MUST level met)
64
- - ⚠️ Warning (SHOULD level met)
65
- - 💡 Info (MAY level met)
43
+ | Level | Match is true | Match is false | Missing method | Other exception |
44
+ |--------|---------------|----------------|----------------|-----------------|
45
+ | MUST | success | failure | error | error |
46
+ | SHOULD | success | warning | error | error |
47
+ | MAY | success | failure | info | error |
66
48
 
67
- - **Fail Results:**
68
- - ❌ Failure (requirement not met)
69
- - 💥 Error (unexpected exception)
49
+ A negation swaps the first two columns. A success, a warning and an info pass (`passed?` is true); a failure and an error do not.
70
50
 
71
- ## Usage Examples
51
+ A missing method is a `NoMethodError` raised by `match?` whose receiver is the very value the block returned (the last one, when the matcher calls the block more than once): `Spectus.may(Matchi::Predicate.new(:be_blank)).call { "" }` is an info when `String#blank?` does not exist, a success or a failure when it does. A `NoMethodError` raised by the block itself, or on another object, is an error. Spectus does not know which method the matcher meant to test, so the rule has its limits: a private method counts as missing, as does a method that exists but calls a missing one on `self`, or a missing method the matcher's own code calls on the value.
72
52
 
73
- ### Testing Required Behavior
53
+ `match?` must answer `true` or `false`: any other answer is an error, as if `match?` had raised a `TypeError`.
74
54
 
75
- ```ruby
76
- test = Spectus.must Matchi::Be.new(1)
77
- test.call { "🦇".size } # Must be exactly 1
78
- ```
55
+ ## Results
79
56
 
80
- ### Testing Recommended Behavior
57
+ A `Spectus::Result` is plain data, frozen: symbols, booleans and frozen strings in UTF-8. It can be marshalled, shared between ractors and compared, and nothing in it runs user code again.
81
58
 
82
- ```ruby
83
- test = Spectus.should Matchi::Be.new(0.3)
84
- test.call { 0.1 + 0.2 } # Should be close to 0.3
85
- ```
59
+ | Member | Content |
60
+ |-----------------|---------|
61
+ | `level` | `:MUST`, `:SHOULD` or `:MAY` |
62
+ | `negate` | `true` or `false` |
63
+ | `outcome` | `:success`, `:warning`, `:info`, `:failure` or `:error` |
64
+ | `description` | the matcher, as its `to_s` wrote it: `eq 42` |
65
+ | `actual` | the value the block returned, as its `inspect` wrote it, or the exception it raised, whether the matcher rescued it or not; `nil` when the matcher did not call the block |
66
+ | `error_class` | the class of the exception that came out of `match?`, or `TypeError` for an answer that was not `true` or `false`; `nil` otherwise |
67
+ | `error_message` | its message |
68
+ | `backtrace` | its backtrace, when it has one, library frames included: a runner filters by path |
86
69
 
87
- ### Testing Optional Features
70
+ `summary` writes `expected ACTUAL to DESCRIPTION`, with `not` for a negation and without the actual value when the block was not called, or `CLASS: MESSAGE` for an exception. `to_s` puts the outcome first: `Success: expected 42 to eq 42`, `Info: NoMethodError: undefined method 'blank?' for an instance of String` (as Ruby 3.4 writes it). No letter, emoji or colour: a runner derives them from `outcome`.
88
71
 
89
- ```ruby
90
- test = Spectus.may Matchi::Be.new(true)
91
- test.call { [].blank? } # May implement blank? method
92
- ```
72
+ The texts are read defensively: an `inspect` or a `message` that raises or does not answer a `String` gives a fixed text (`an object of Point`, `a message that cannot be read`), a class without a name is `an anonymous exception`, a `backtrace` that raises or is not an `Array` of `String` is `nil`, and bytes that are not valid UTF-8 become U+FFFD. A result carries the level and the negation of its requirement, so that a runner holding results alone can still write the requirement they answer; a runner may also build a `Spectus::Result` of its own for what never reached `call`.
93
73
 
94
- ## Advanced Usage
74
+ ## Exceptions
95
75
 
96
- <details>
97
- <summary>Click to expand custom matcher example</summary>
76
+ `call` raises `ArgumentError` without a block and `TypeError` when the `to_s` of the matcher is not a `String`; the matcher is test code, trusted, and what its `to_s` raises goes through. The block and `match?` run under the policy of Defi: the exceptions a method raises on its own, a `StandardError`, a `ScriptError` (such as `NotImplementedError`), a `SystemStackError` or the `SystemExit` of an `exit`, end in the result (as an error, or as an info for a MAY), while an `Interrupt`, a `SignalException`, a `NoMemoryError`, the exception a `Timeout` uses to end its block and any other subclass of `Exception` go through, whether the block or the matcher raised them. Spectus never sees what a matcher rescues itself: in matchi 5.0, `Matchi::RaiseException` rescues `Exception`, so an `exit` inside its block is not an error.
98
77
 
99
- ```ruby
100
- class PositiveNumber
101
- def match?
102
- yield.positive?
103
- end
104
- end
105
-
106
- test = Spectus.must PositiveNumber.new
107
- test.call { 42 } # => Pass
108
- ```
109
- </details>
78
+ The block runs inside `match?`, as many times as the matcher calls it, and without arguments: a lambda that expects some raises `ArgumentError`, which ends in the result. `actual` is the block's last value. The exception it raises is raised again inside the matcher, the same object with its own cause, as Defi does it.
110
79
 
111
- <details>
112
- <summary>Click to expand integration example</summary>
80
+ ## Changes in 6.0
113
81
 
114
- ```ruby
115
- require "spectus"
116
- require "matchi"
82
+ Compared with 5.0.2:
117
83
 
118
- RSpec.describe Calculator do
119
- it "must perform exact arithmetic" do
120
- test = Spectus.must Matchi::Eq.new(4)
121
- expect { test.call { 2 + 2 } }.not_to raise_error
122
- end
123
- end
124
- ```
125
- </details>
84
+ - `call` returns a `Spectus::Result` and never raises for a failed expectation, where 5.0.2 returned an `Expresenter::Pass` or raised an `Expresenter::Fail`: read `passed?` or `outcome`. An `expect { requirement.call { … } }.not_to raise_error` written for 5.0.2 passes whatever happens.
85
+ - `Spectus::Requirement` is one `Data` class with a `level`, in place of `Requirement::Required`, `Recommended` and `Optional`; `Spectus::Requirement.new(level:, negate:, matcher:)` builds one, with an `ArgumentError` for a MAY that is negated, a level other than the three symbols, a negation that is not `true` or `false`, or a matcher without `match?`. `call` without a block raises `ArgumentError`, where 5.0.2 passed.
86
+ - `match?` must answer `true` or `false`: 5.0.2 passed any truthy value and, when negated, `nil`. A missing method is a `NoMethodError` on the value the block returned: 5.0.2 counted every `NoMethodError` as one. A `Timeout` and an `Interrupt` go through, where 5.0.2 swallowed them; a `SystemExit` is an error, as it was.
87
+ - The result exposes `description`, `actual`, `error_class`, `error_message` and `backtrace` as strings, `summary` and `to_s` without a trailing period, the outcome as its title; `char`, `emoji`, `colored_char`, `colored_string`, `to_sym`, `success?`, `warning?`, `info?`, `failure?` and `error?` are gone, as are the dependencies on test_tube and expresenter.
88
+ - Ruby 3.3 or later; tested on 3.3, 3.4, 4.0 and head.
126
89
 
127
- ## Related Projects
90
+ ## Versioning
128
91
 
129
- - [Matchi](https://github.com/fixrb/matchi) - Collection of compatible matchers
130
- - [Test Tube](https://github.com/fixrb/test_tube) - Underlying test execution engine
131
- - [Expresenter](https://github.com/fixrb/expresenter) - Test result presentation
92
+ Spectus follows [Semantic Versioning 2.0](https://semver.org/).
132
93
 
133
94
  ## License
134
95
 
135
- Released under the [MIT License](LICENSE.md).
136
-
137
- ## Support
138
-
139
- - Issues: [GitHub Issues](https://github.com/fixrb/spectus/issues)
140
- - Documentation: [RubyDoc](https://rubydoc.info/github/fixrb/spectus/main)
141
- - Blog Post: [Medium Article](https://cyrilllllll.medium.com/a-spectus-tutorial-expectations-with-rfc-2119-compliance-1fc769861c1)
96
+ The [gem](https://rubygems.org/gems/spectus) is available as open source under the terms of the [MIT License](https://github.com/fixrb/spectus/raw/main/LICENSE.md).
142
97
 
143
98
  ## Sponsors
144
99
 
@@ -1,20 +1,121 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "defi"
4
+
5
+ require_relative "result"
6
+ require_relative "text"
7
+
3
8
  module Spectus
4
- # Namespace for RFC 2119 requirement levels.
5
- #
6
- # This module contains different requirement level implementations:
7
- # - Required (MUST/MUST NOT)
8
- # - Recommended (SHOULD/SHOULD NOT)
9
- # - Optional (MAY)
10
- #
11
- # Each level has its own rules for determining test success/failure.
9
+ # The levels of RFC 2119, each with the outcome of a failed match. The
10
+ # keys are compared by identity: a level is one of these three symbols,
11
+ # not an object that hashes like one.
12
+ LEVELS = { MUST: :failure, SHOULD: :warning, MAY: :failure }.compare_by_identity.freeze
13
+
14
+ # The outcome of a missing method, level by level.
15
+ MISSING = { MUST: :error, SHOULD: :error, MAY: :info }.freeze
16
+
17
+ private_constant :LEVELS
18
+ private_constant :MISSING
19
+
20
+ # An expectation: a level, a negation and a matcher, frozen. The matcher
21
+ # is test code, trusted: it is kept as it is, its `match?` is called with
22
+ # the block, and its `to_s` describes it.
12
23
  #
13
- # @api private
14
- module Requirement
24
+ # @!attribute [r] level
25
+ # @return [Symbol] `:MUST`, `:SHOULD` or `:MAY`
26
+ # @!attribute [r] negate
27
+ # @return [Boolean] whether the match is expected to fail
28
+ # @!attribute [r] matcher
29
+ # @return [#match?] the matcher
30
+ Requirement = ::Data.define(:level, :negate, :matcher) do
31
+ # @param level [Symbol] `:MUST`, `:SHOULD` or `:MAY`
32
+ # @param negate [Boolean] whether the match is expected to fail; a MAY
33
+ # has no negative form
34
+ # @param matcher [#match?] the matcher
35
+ # @raise [ArgumentError] for any other level or negation, or a matcher
36
+ # that does not respond to `match?` (its own `respond_to?` is not asked)
37
+ def initialize(level:, negate:, matcher:)
38
+ raise ::ArgumentError, "the level must be :MUST, :SHOULD or :MAY" unless LEVELS.key?(level)
39
+ raise ::ArgumentError, "negate must be true or false" unless true.equal?(negate) || false.equal?(negate)
40
+ raise ::ArgumentError, "a MAY has no negative form" if negate && level.equal?(:MAY)
41
+ unless ::Kernel.instance_method(:respond_to?).bind_call(matcher, :match?)
42
+ raise ::ArgumentError, "the matcher must respond to match?"
43
+ end
44
+
45
+ super
46
+ end
47
+
48
+ # Runs the matcher with the block, and says how it went. Raises nothing
49
+ # of its own: the exceptions a method raises on its own (those Defi
50
+ # keeps, a `StandardError`, a `ScriptError`, a `SystemStackError` or a
51
+ # `SystemExit`) end in the result, while an `Interrupt`, a signal, a
52
+ # `NoMemoryError` and the end of a `Timeout` go through.
53
+ #
54
+ # @yieldreturn [Object] the actual value
55
+ # @return [Spectus::Result]
56
+ # @raise [ArgumentError] without a block
57
+ # @raise [TypeError] when the `to_s` of the matcher is not a String
58
+ def call(&block)
59
+ raise ::ArgumentError, "a block must be given" unless block
60
+
61
+ description = matcher.to_s
62
+ raise ::TypeError, "the to_s of the matcher must be a String" unless ::String === description
63
+
64
+ description = Text.utf8(description)
65
+ produced = nil
66
+ answer = ::Defi::Challenge.new(:match?) do
67
+ produced = ::Defi::Challenge.new(:call).to(block)
68
+ produced.call
69
+ end.to(matcher)
70
+ result(description, produced, answer)
71
+ end
72
+
73
+ private
74
+
75
+ # The result, from what the block produced (nil when the matcher did not
76
+ # call it) and what `match?` answered or raised.
77
+ def result(description, produced, answer)
78
+ actual = produced && Text.object(produced.object)
79
+ error_class, error_message, backtrace = error(answer)
80
+ Result.new(level:, negate:, outcome: outcome(produced, answer), description:, actual:, error_class:,
81
+ error_message:, backtrace:)
82
+ end
83
+
84
+ # The outcome: a method missing on the value the block produced is read
85
+ # by the level; an answer of true or false is read with the negation, an
86
+ # answer equal to the negation being a failed match; anything else is an
87
+ # error.
88
+ def outcome(produced, answer)
89
+ return MISSING.fetch(level) if missing_method?(produced, answer)
90
+ return :error unless verdict?(answer)
91
+
92
+ negate.equal?(answer.object) ? LEVELS.fetch(level) : :success
93
+ end
94
+
95
+ # Whether `match?` answered true or false, which no exception is.
96
+ def verdict?(answer)
97
+ true.equal?(answer.object) || false.equal?(answer.object)
98
+ end
99
+
100
+ # Whether `match?` raised a NoMethodError whose receiver is the value the
101
+ # block produced, compared by identity as BasicObject does. A
102
+ # NoMethodError built by hand may have no receiver.
103
+ def missing_method?(produced, answer)
104
+ return false unless produced && !produced.raised? && answer.raised? && ::NoMethodError === answer.object
105
+
106
+ receiver = ::NameError.instance_method(:receiver).bind_call(answer.object)
107
+ ::BasicObject.instance_method(:equal?).bind_call(receiver, produced.object)
108
+ rescue ::ArgumentError
109
+ false
110
+ end
111
+
112
+ # The texts of the exception, when there is one: the one `match?` raised,
113
+ # or a TypeError for an answer that is not true or false.
114
+ def error(answer)
115
+ return Text.exception(answer.object) if answer.raised?
116
+ return [nil, nil, nil] if verdict?(answer)
117
+
118
+ ["TypeError", "match? answered #{Text.object(answer.object)}, not true or false".freeze, nil]
119
+ end
15
120
  end
16
121
  end
17
-
18
- require_relative File.join("requirement", "required")
19
- require_relative File.join("requirement", "recommended")
20
- require_relative File.join("requirement", "optional")
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Spectus
4
+ # How an expectation went: plain data, frozen, made of symbols, booleans
5
+ # and frozen UTF-8 strings. A result can be marshalled, shared between
6
+ # ractors, compared and printed without running any user code. It carries
7
+ # the level and the negation of its requirement, so that a runner holding
8
+ # results alone can still write the requirement they answer.
9
+ #
10
+ # @!attribute [r] level
11
+ # @return [Symbol] `:MUST`, `:SHOULD` or `:MAY`
12
+ # @!attribute [r] negate
13
+ # @return [Boolean] whether the match was expected to fail
14
+ # @!attribute [r] outcome
15
+ # @return [Symbol] `:success`, `:warning`, `:info`, `:failure` or `:error`
16
+ # @!attribute [r] description
17
+ # @return [String] the matcher, as its `to_s` wrote it
18
+ # @!attribute [r] actual
19
+ # @return [String, nil] the value the block produced, as its `inspect`
20
+ # wrote it, or the exception it raised (which is also the error when
21
+ # the matcher let it through); `nil` when the matcher did not call the
22
+ # block
23
+ # @!attribute [r] error_class
24
+ # @return [String, nil] the class of the exception that came out of
25
+ # `match?`, or `TypeError` for an answer that was not true or false
26
+ # @!attribute [r] error_message
27
+ # @return [String, nil] its message
28
+ # @!attribute [r] backtrace
29
+ # @return [Array<String>, nil] its backtrace, when it has one
30
+ Result = ::Data.define(:level, :negate, :outcome, :description, :actual, :error_class, :error_message, :backtrace) do
31
+ # @return [Boolean] whether the expectation is met: a success, a warning
32
+ # or an info
33
+ def passed?
34
+ %i[success warning info].include?(outcome)
35
+ end
36
+
37
+ # @return [String] what happened: `expected ACTUAL to DESCRIPTION`, with
38
+ # `not` when negated and without the actual value when the block was
39
+ # not called, or `CLASS: MESSAGE` for an exception
40
+ def summary
41
+ return "#{error_class}: #{error_message}" if error_class
42
+
43
+ ["expected", actual, ("not" if negate), "to", description].compact.join(" ")
44
+ end
45
+
46
+ # @return [String] the outcome as a title, then the summary:
47
+ # `Success: expected 42 to eq 42`
48
+ def to_s
49
+ "#{outcome.to_s.capitalize}: #{summary}"
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "defi"
4
+
5
+ module Spectus
6
+ # Texts read from user code, which may raise, return anything or hold
7
+ # bytes in any encoding: each one comes back as a frozen String in UTF-8,
8
+ # or as a stated fallback.
9
+ #
10
+ # @api private
11
+ module Text
12
+ # @param object [Object] any object, a BasicObject included
13
+ # @return [String] its inspect, or `an object of CLASS` when the inspect
14
+ # raises or is not a String (`an anonymous class` without a name)
15
+ def self.object(object)
16
+ text = object.inspect
17
+ ::String === text ? utf8(text) : fallback(object)
18
+ rescue *::Defi::Value::RAISED
19
+ fallback(object)
20
+ end
21
+
22
+ # @param exception [Exception]
23
+ # @return [Array(String, String, Array<String>)] the name of its class
24
+ # (`an anonymous exception` without a name), its message (`a message
25
+ # that cannot be read` when it raises or is not a String) and its
26
+ # backtrace, `nil` in place of the latter when it has none, it raises
27
+ # or it is not an Array of Strings
28
+ def self.exception(exception)
29
+ [class_name(exception) || "an anonymous exception", message(exception), backtrace(exception)]
30
+ end
31
+
32
+ # The text of an object whose inspect cannot be read.
33
+ def self.fallback(object)
34
+ "an object of #{class_name(object) || "an anonymous class"}".freeze
35
+ end
36
+
37
+ # The name of the class of an object, read as Kernel and Module do, or
38
+ # nil for an anonymous class.
39
+ def self.class_name(object)
40
+ klass = ::Kernel.instance_method(:class).bind_call(object)
41
+ name = ::Module.instance_method(:name).bind_call(klass)
42
+ name && utf8(name)
43
+ end
44
+
45
+ # The message of an exception, which user code may redefine.
46
+ def self.message(exception)
47
+ text = exception.message
48
+ ::String === text ? utf8(text) : "a message that cannot be read"
49
+ rescue *::Defi::Value::RAISED
50
+ "a message that cannot be read"
51
+ end
52
+
53
+ # The backtrace of an exception, which user code may redefine too: a
54
+ # plain copy of the Array is asked, not a subclass.
55
+ def self.backtrace(exception)
56
+ lines = exception.backtrace
57
+ return unless ::Array === lines
58
+
59
+ lines = ::Array.new(lines)
60
+ return unless lines.all?(::String)
61
+
62
+ lines.map { |line| utf8(line) }.freeze
63
+ rescue *::Defi::Value::RAISED
64
+ nil
65
+ end
66
+
67
+ # @param text [String] a String, in any encoding, of any class
68
+ # @return [String] a plain copy, valid UTF-8, frozen: invalid bytes and
69
+ # characters UTF-8 cannot hold become U+FFFD, and a String in an
70
+ # encoding Ruby cannot convert is read as UTF-8 bytes
71
+ def self.utf8(text)
72
+ copy = ::String.new(text)
73
+ begin
74
+ copy.encode(::Encoding::UTF_8, invalid: :replace, undef: :replace)
75
+ rescue ::EncodingError
76
+ copy.force_encoding(::Encoding::UTF_8).scrub
77
+ end.freeze
78
+ end
79
+
80
+ private_class_method :fallback, :class_name, :message, :backtrace
81
+ end
82
+
83
+ private_constant :Text
84
+ end
data/lib/spectus.rb CHANGED
@@ -1,208 +1,46 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative File.join("spectus", "requirement")
3
+ require_relative "spectus/requirement"
4
4
 
5
- # A Ruby library for defining expectations with precision using RFC 2119 compliance levels.
5
+ # Expectations with the requirement levels of RFC 2119. A requirement is a
6
+ # level (MUST, SHOULD or MAY), a negation and a matcher; called with a block,
7
+ # it gives a result, a value that says how the expectation went, and never
8
+ # raises for an expectation that is not met.
6
9
  #
7
- # This module provides methods to define expectations according to different requirement
8
- # levels (MUST, SHOULD, MAY). Each method accepts a matcher object that responds to `match?`
9
- # and follows the block-passing protocol.
10
+ # @example
11
+ # require "matchi"
10
12
  #
11
- # While the {https://github.com/fixrb/matchi Matchi gem} provides a collection of ready-to-use
12
- # matchers, you can create your own custom matchers:
13
- #
14
- # @example Creating a custom matcher
15
- # class BeTheAnswer
16
- # def match?
17
- # 42.equal?(yield)
18
- # end
19
- # end
20
- #
21
- # test = Spectus.must BeTheAnswer.new
22
- # test.call { 42 } # => pass
23
- # test.call { 41 } # => fail
24
- #
25
- # @example Using with Matchi gem
26
- # require "spectus"
27
- # require "matchi/eq"
28
- #
29
- # test = Spectus.must Matchi::Eq.new(42)
30
- # test.call { 42 } # => pass
31
- #
32
- # @see https://www.ietf.org/rfc/rfc2119.txt RFC 2119 specification
33
- # @see https://github.com/fixrb/matchi Matchi - Collection of compatible matchers
13
+ # result = Spectus.must(Matchi::Eq.new(42)).call { 6 * 7 }
14
+ # result.passed? # => true
15
+ # result.to_s # => "Success: expected 42 to eq 42"
34
16
  module Spectus
35
- # Defines an absolute requirement that must be satisfied by the implementation.
36
- # This represents the RFC 2119 "MUST" level - an absolute requirement of the specification.
37
- #
38
- # @example With a custom matcher
39
- # class PositiveNumber
40
- # def match?
41
- # (yield).positive?
42
- # end
43
- # end
44
- #
45
- # test = Spectus.must PositiveNumber.new
46
- # test.call { 42 }
47
- # # => #<Expresenter::Pass actual: 42, ...>
48
- #
49
- # @example With Matchi gem
50
- # require "spectus"
51
- # require "matchi/eq"
52
- #
53
- # test = Spectus.must Matchi::Eq.new(42)
54
- # test.call { 42 }
55
- # # => #<Expresenter::Pass actual: 42, ...>
56
- #
57
- # @param matcher [#match?] Any object that implements the matcher protocol:
58
- # - Responds to `match?`
59
- # - Accepts a block in `match?` that provides the actual value
60
- # @return [Requirement::Required] An absolute requirement level instance
61
- # @raise [ArgumentError] If matcher doesn't respond to match?
62
- #
63
- # @api public
17
+ # @param matcher [#match?] the matcher
18
+ # @return [Spectus::Requirement] an absolute requirement
64
19
  def self.must(matcher)
65
- raise ::ArgumentError, "matcher must respond to match?" unless matcher.respond_to?(:match?)
66
-
67
- Requirement::Required.new(negate: false, matcher:)
20
+ Requirement.new(level: :MUST, negate: false, matcher:)
68
21
  end
69
22
 
70
- # Defines an absolute prohibition in the specification.
71
- # This represents the RFC 2119 "MUST NOT" level - an absolute prohibition.
72
- #
73
- # @example With a custom matcher
74
- # class NegativeNumber
75
- # def match?
76
- # (yield).negative?
77
- # end
78
- # end
79
- #
80
- # test = Spectus.must_not NegativeNumber.new
81
- # test.call { 42 }
82
- # # => #<Expresenter::Pass actual: 42, ...>
83
- #
84
- # @example With Matchi gem
85
- # require "spectus"
86
- # require "matchi/be"
87
- #
88
- # test = Spectus.must_not Matchi::Be.new(0)
89
- # test.call { 42 }
90
- # # => #<Expresenter::Pass actual: 42, ...>
91
- #
92
- # @param matcher [#match?] Any object that implements the matcher protocol
93
- # @return [Requirement::Required] An absolute prohibition level instance
94
- # @raise [ArgumentError] If matcher doesn't respond to match?
23
+ # @param matcher [#match?] the matcher
24
+ # @return [Spectus::Requirement] an absolute prohibition
95
25
  def self.must_not(matcher)
96
- raise ::ArgumentError, "matcher must respond to match?" unless matcher.respond_to?(:match?)
97
-
98
- Requirement::Required.new(negate: true, matcher:)
26
+ Requirement.new(level: :MUST, negate: true, matcher:)
99
27
  end
100
28
 
101
- # Defines a recommended requirement that should be satisfied unless there are valid reasons not to.
102
- # This represents the RFC 2119 "SHOULD" level - where valid reasons may exist to ignore
103
- # a particular item, but the implications must be understood and weighed.
104
- #
105
- # @example With a custom matcher
106
- # class EvenNumber
107
- # def match?
108
- # (yield).even?
109
- # end
110
- # end
111
- #
112
- # test = Spectus.should EvenNumber.new
113
- # test.call { 42 }
114
- # # => #<Expresenter::Pass actual: 42, ...>
115
- #
116
- # @example With Matchi gem
117
- # require "spectus"
118
- # require "matchi/be"
119
- #
120
- # test = Spectus.should Matchi::Be.new(:even?)
121
- # test.call { 42 }
122
- # # => #<Expresenter::Pass actual: 42, ...>
123
- #
124
- # @param matcher [#match?] Any object that implements the matcher protocol
125
- # @return [Requirement::Recommended] A recommended requirement level instance
126
- # @raise [ArgumentError] If matcher doesn't respond to match?
29
+ # @param matcher [#match?] the matcher
30
+ # @return [Spectus::Requirement] a recommendation
127
31
  def self.should(matcher)
128
- raise ::ArgumentError, "matcher must respond to match?" unless matcher.respond_to?(:match?)
129
-
130
- Requirement::Recommended.new(negate: false, matcher:)
32
+ Requirement.new(level: :SHOULD, negate: false, matcher:)
131
33
  end
132
34
 
133
- # Defines a behavior that is not recommended but may be acceptable in specific circumstances.
134
- # This represents the RFC 2119 "SHOULD NOT" level - where particular behavior may be acceptable
135
- # but the implications should be understood and the case carefully weighed.
136
- #
137
- # @example With a custom matcher
138
- # class RaisesError
139
- # def match?
140
- # yield
141
- # false
142
- # rescue
143
- # true
144
- # end
145
- # end
146
- #
147
- # test = Spectus.should_not RaisesError.new
148
- # test.call { 42 }
149
- # # => #<Expresenter::Pass actual: 42, ...>
150
- #
151
- # @example With Matchi gem
152
- # require "spectus"
153
- # require "matchi/raise_exception"
154
- #
155
- # test = Spectus.should_not Matchi::RaiseException.new(StandardError)
156
- # test.call { 42 }
157
- # # => #<Expresenter::Pass actual: 42, ...>
158
- #
159
- # @param matcher [#match?] Any object that implements the matcher protocol
160
- # @return [Requirement::Recommended] A not recommended requirement level instance
161
- # @raise [ArgumentError] If matcher doesn't respond to match?
35
+ # @param matcher [#match?] the matcher
36
+ # @return [Spectus::Requirement] a negated recommendation
162
37
  def self.should_not(matcher)
163
- raise ::ArgumentError, "matcher must respond to match?" unless matcher.respond_to?(:match?)
164
-
165
- Requirement::Recommended.new(negate: true, matcher:)
38
+ Requirement.new(level: :SHOULD, negate: true, matcher:)
166
39
  end
167
40
 
168
- # Defines an optional feature or behavior.
169
- # This represents the RFC 2119 "MAY" level - where an item is truly optional.
170
- # Implementations can freely choose whether to include the item based on their
171
- # specific needs, while maintaining interoperability with other implementations.
172
- #
173
- # For MAY requirements, a test passes in two cases:
174
- # 1. When a NoMethodError is raised, indicating the feature is not implemented
175
- # 2. When the feature is implemented and the test succeeds
176
- #
177
- # @example With a custom matcher testing an optional method
178
- # class RespondsTo
179
- # def initialize(method)
180
- # @method = method
181
- # end
182
- #
183
- # def match?
184
- # (yield).respond_to?(@method)
185
- # end
186
- # end
187
- #
188
- # test = Spectus.may RespondsTo.new(:to_h)
189
- # test.call { {} } # => pass (feature is implemented)
190
- # test.call { BasicObject.new } # => pass (NoMethodError - feature not implemented)
191
- #
192
- # @example With Matchi gem
193
- # require "spectus"
194
- # require "matchi/predicate"
195
- #
196
- # test = Spectus.may Matchi::Predicate.new(:be_frozen)
197
- # test.call { "".freeze } # => pass (feature is implemented)
198
- # test.call { BasicObject.new } # => pass (NoMethodError - feature not implemented)
199
- #
200
- # @param matcher [#match?] Any object that implements the matcher protocol
201
- # @return [Requirement::Optional] An optional requirement level instance
202
- # @raise [ArgumentError] If matcher doesn't respond to match?
41
+ # @param matcher [#match?] the matcher
42
+ # @return [Spectus::Requirement] an option, which has no negative form
203
43
  def self.may(matcher)
204
- raise ::ArgumentError, "matcher must respond to match?" unless matcher.respond_to?(:match?)
205
-
206
- Requirement::Optional.new(negate: false, matcher:)
44
+ Requirement.new(level: :MAY, negate: false, matcher:)
207
45
  end
208
46
  end
metadata CHANGED
@@ -1,44 +1,30 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: spectus
3
3
  version: !ruby/object:Gem::Version
4
- version: 5.0.2
4
+ version: 6.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Cyril Kato
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2025-01-01 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
- name: expresenter
13
+ name: defi
15
14
  requirement: !ruby/object:Gem::Requirement
16
15
  requirements:
17
16
  - - "~>"
18
17
  - !ruby/object:Gem::Version
19
- version: 1.5.1
18
+ version: '4.0'
20
19
  type: :runtime
21
20
  prerelease: false
22
21
  version_requirements: !ruby/object:Gem::Requirement
23
22
  requirements:
24
23
  - - "~>"
25
24
  - !ruby/object:Gem::Version
26
- version: 1.5.1
27
- - !ruby/object:Gem::Dependency
28
- name: test_tube
29
- requirement: !ruby/object:Gem::Requirement
30
- requirements:
31
- - - "~>"
32
- - !ruby/object:Gem::Version
33
- version: 4.0.1
34
- type: :runtime
35
- prerelease: false
36
- version_requirements: !ruby/object:Gem::Requirement
37
- requirements:
38
- - - "~>"
39
- - !ruby/object:Gem::Version
40
- version: 4.0.1
41
- description: "Expectation library with RFC 2119's requirement levels \U0001F6A5"
25
+ version: '4.0'
26
+ description: An expectation is a level (MUST, SHOULD or MAY), a negation and a matcher;
27
+ called with a block, it gives a result that says how it went, without raising.
42
28
  email: contact@cyril.email
43
29
  executables: []
44
30
  extensions: []
@@ -48,16 +34,17 @@ files:
48
34
  - README.md
49
35
  - lib/spectus.rb
50
36
  - lib/spectus/requirement.rb
51
- - lib/spectus/requirement/base.rb
52
- - lib/spectus/requirement/optional.rb
53
- - lib/spectus/requirement/recommended.rb
54
- - lib/spectus/requirement/required.rb
55
- homepage: https://github.com/fixrb/spectus
37
+ - lib/spectus/result.rb
38
+ - lib/spectus/text.rb
39
+ homepage: https://fixrb.dev/gems/spectus/
56
40
  licenses:
57
41
  - MIT
58
42
  metadata:
43
+ bug_tracker_uri: https://github.com/fixrb/spectus/issues
44
+ changelog_uri: https://github.com/fixrb/spectus#changes-in-60
45
+ documentation_uri: https://rubydoc.info/gems/spectus
59
46
  rubygems_mfa_required: 'true'
60
- post_install_message:
47
+ source_code_uri: https://github.com/fixrb/spectus
61
48
  rdoc_options: []
62
49
  require_paths:
63
50
  - lib
@@ -65,15 +52,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
65
52
  requirements:
66
53
  - - ">="
67
54
  - !ruby/object:Gem::Version
68
- version: 3.1.0
55
+ version: 3.3.0
69
56
  required_rubygems_version: !ruby/object:Gem::Requirement
70
57
  requirements:
71
58
  - - ">="
72
59
  - !ruby/object:Gem::Version
73
60
  version: '0'
74
61
  requirements: []
75
- rubygems_version: 3.3.27
76
- signing_key:
62
+ rubygems_version: 4.0.23
77
63
  specification_version: 4
78
- summary: "Expectation library with RFC 2119's requirement levels \U0001F6A5"
64
+ summary: Expectations with the requirement levels of RFC 2119
79
65
  test_files: []
@@ -1,75 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require "expresenter"
4
- require "test_tube"
5
-
6
- module Spectus
7
- # Namespace for the requirement levels.
8
- module Requirement
9
- # Base class for implementing RFC 2119 requirement levels.
10
- #
11
- # This class provides the core functionality for running tests against
12
- # different requirement levels (MUST, SHOULD, MAY). It uses TestTube for
13
- # test execution and Expresenter for result presentation.
14
- #
15
- # @see https://github.com/fixrb/test_tube Test execution
16
- # @see https://github.com/fixrb/expresenter Result presentation
17
- class Base
18
- # Initialize the requirement level class.
19
- #
20
- # @param matcher [#match?] The matcher used to evaluate the test
21
- # @param negate [Boolean] When true, inverts the matcher's result
22
- #
23
- # @raise [ArgumentError] If matcher doesn't respond to match?
24
- def initialize(matcher:, negate:)
25
- raise ::ArgumentError, "matcher must respond to match?" unless matcher.respond_to?(:match?)
26
-
27
- @matcher = matcher
28
- @negate = negate
29
- end
30
-
31
- # Execute the test and return its result.
32
- #
33
- # Runs the provided block through the matcher and evaluates the result
34
- # according to the requirement level's rules. The result is presented
35
- # through an Expresenter instance containing all test details.
36
- #
37
- # @example
38
- # test = Base.new(matcher: SomeMatcher.new, negate: false)
39
- # test.call { some_value }
40
- # # => #<Expresenter::Pass actual: some_value, ...>
41
- #
42
- # @yield The block containing the code to test
43
- # @raise [::Expresenter::Fail] When the test fails
44
- # @return [::Expresenter::Pass] When the test passes
45
- #
46
- # @api public
47
- def call(&)
48
- test = ::TestTube.invoke(matcher: @matcher, negate: @negate, &)
49
-
50
- ::Expresenter.call(passed?(test)).with(
51
- actual: test.actual,
52
- definition: @matcher.to_s,
53
- error: test.error,
54
- got: test.got,
55
- level: self.class.level,
56
- negate: @negate
57
- )
58
- end
59
-
60
- private
61
-
62
- # Determine if the test passed according to the requirement level's rules.
63
- #
64
- # This base implementation considers the test passed if the matcher
65
- # returned true. Subclasses may override this method to implement
66
- # specific requirement level rules.
67
- #
68
- # @param test [::TestTube::Base] The test execution state
69
- # @return [Boolean] true if the test passed, false otherwise
70
- def passed?(test)
71
- test.got.equal?(true)
72
- end
73
- end
74
- end
75
- end
@@ -1,46 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require_relative "base"
4
-
5
- module Spectus
6
- module Requirement
7
- # Implementation of MAY requirements from RFC 2119.
8
- #
9
- # This level represents optional features. A test at this level
10
- # passes in two cases:
11
- # - When the feature is implemented and the matcher returns true
12
- # - When NoMethodError is raised, indicating the feature is not implemented
13
- #
14
- # @example Testing a MAY requirement with implemented feature
15
- # test = Optional.new(matcher: some_matcher, negate: false)
16
- # test.call { implemented_feature } # Passes if matcher returns true
17
- #
18
- # @example Testing a MAY requirement with unimplemented feature
19
- # test = Optional.new(matcher: some_matcher, negate: false)
20
- # test.call { unimplemented_feature } # Passes if NoMethodError is raised
21
- #
22
- # @see https://www.ietf.org/rfc/rfc2119.txt RFC 2119 MAY keyword
23
- class Optional < Base
24
- # The RFC 2119 keyword for this requirement level.
25
- #
26
- # @return [Symbol] :MAY indicating an optional requirement
27
- # @api public
28
- def self.level
29
- :MAY
30
- end
31
-
32
- private
33
-
34
- # Determine if the test passed according to MAY requirement rules.
35
- # A test passes if either:
36
- # - The base matcher validation passes (super)
37
- # - The feature is not implemented (NoMethodError)
38
- #
39
- # @param (see Base#passed?)
40
- # @return (see Base#passed?)
41
- def passed?(test)
42
- super || test.error.is_a?(::NoMethodError)
43
- end
44
- end
45
- end
46
- end
@@ -1,46 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require_relative "base"
4
-
5
- module Spectus
6
- module Requirement
7
- # Implementation of SHOULD/SHOULD NOT requirements from RFC 2119.
8
- #
9
- # This level is less strict than MUST requirements. A test at this level
10
- # passes in two cases:
11
- # - When the matcher returns the expected result
12
- # - When no error was raised during the test
13
- #
14
- # @example Testing a SHOULD requirement
15
- # test = Recommended.new(matcher: some_matcher, negate: false)
16
- # test.call { value } # Passes if matcher returns true or no error occurs
17
- #
18
- # @example Testing a SHOULD NOT requirement
19
- # test = Recommended.new(matcher: some_matcher, negate: true)
20
- # test.call { value } # Passes if matcher returns false or no error occurs
21
- #
22
- # @see https://www.ietf.org/rfc/rfc2119.txt RFC 2119 SHOULD/SHOULD NOT keywords
23
- class Recommended < Base
24
- # The RFC 2119 keyword for this requirement level.
25
- #
26
- # @return [Symbol] :SHOULD indicating a recommended requirement
27
- # @api public
28
- def self.level
29
- :SHOULD
30
- end
31
-
32
- private
33
-
34
- # Determine if the test passed according to SHOULD requirement rules.
35
- # A test passes if either:
36
- # - The base matcher validation passes (super)
37
- # - No error occurred during test execution
38
- #
39
- # @param (see Base#passed?)
40
- # @return (see Base#passed?)
41
- def passed?(test)
42
- super || test.error.nil?
43
- end
44
- end
45
- end
46
- end
@@ -1,36 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require_relative "base"
4
-
5
- module Spectus
6
- module Requirement
7
- # Implementation of MUST/MUST NOT requirements from RFC 2119.
8
- #
9
- # This level represents an absolute requirement - tests at this level
10
- # must pass without any exceptions or conditions. Unlike SHOULD or MAY levels,
11
- # there is no flexibility in what constitutes a passing test.
12
- #
13
- # The test passes only when:
14
- # - MUST: The matcher returns true (when negate: false)
15
- # - MUST NOT: The matcher returns false (when negate: true)
16
- #
17
- # @example Testing a MUST requirement
18
- # test = Required.new(matcher: some_matcher, negate: false)
19
- # test.call { value } # Passes only if matcher returns true
20
- #
21
- # @example Testing a MUST NOT requirement
22
- # test = Required.new(matcher: some_matcher, negate: true)
23
- # test.call { value } # Passes only if matcher returns false
24
- #
25
- # @see https://www.ietf.org/rfc/rfc2119.txt RFC 2119 MUST/MUST NOT keywords
26
- class Required < Base
27
- # The RFC 2119 keyword for this requirement level.
28
- #
29
- # @return [Symbol] :MUST indicating an absolute requirement
30
- # @api public
31
- def self.level
32
- :MUST
33
- end
34
- end
35
- end
36
- end