Documentation
¶
Overview ¶
Package rspec is a pure-Go (no cgo) reimplementation of the deterministic, interpreter-independent core of Ruby's RSpec — the rspec-expectations matchers (their match logic and byte-faithful failure messages) and the rspec-core example-group structure model and formatter output.
Running the bodies of `it` examples and before/after/let/subject hooks is the host's job (rbgo evaluates the Ruby); this library provides the parts that are pure functions of values and results: does a matcher match, what message does it produce, and how does the formatter render a set of results. It is the RSpec backend for go-embedded-ruby, but a standalone, reusable module with no dependency on a Ruby runtime.
Index ¶
- Variables
- func BeWithin(delta float64) *beWithinMatcher
- func ChangeObserved(obs Change) *changeMatcher
- func Expect(actual any, m Matcher, positive bool) (ok bool, message string)
- func Inspect(v any) string
- func RespondTo(methods ...Symbol) *respondToMatcher
- func TotalsLine(examples, failures, pending, errors int) string
- type Change
- type Class
- type Describer
- type Example
- type ExampleGroup
- type Filter
- type Hash
- type Hook
- type HookKind
- type HookScope
- type Matcher
- func All(inner Matcher) Matcher
- func And(left, right Matcher) Matcher
- func BeEqualOp(x any) Matcher
- func BeFalsey() Matcher
- func BeGreaterOrEqual(x any) Matcher
- func BeGreaterThan(x any) Matcher
- func BeInstanceOf(class string) Matcher
- func BeKindOf(class string) Matcher
- func BeLessOrEqual(x any) Matcher
- func BeLessThan(x any) Matcher
- func BeNil() Matcher
- func BeNotEqualOp(x any) Matcher
- func BePredicate(predicate string) Matcher
- func BeTruthy() Matcher
- func ContainExactly(items ...any) Matcher
- func Cover(values ...any) Matcher
- func EndWith(items ...any) Matcher
- func Eq(expected any) Matcher
- func Eql(expected any) Matcher
- func Equal(expected any) Matcher
- func HaveAttributes(attrs *Hash) Matcher
- func Include(items ...any) Matcher
- func Match(pattern any) Matcher
- func MatchArray(items []any) Matcher
- func Or(left, right Matcher) Matcher
- func RaiseErrorObserved(obs RaisedError, class string, message any) Matcher
- func Satisfy(desc, expr string, pred func(any) bool) Matcher
- func StartWith(items ...any) Matcher
- type Module
- type Object
- type Pair
- type RaisedError
- type Range
- type Regexp
- type Reporter
- type Result
- type Status
- type Symbol
- type Timing
Constants ¶
This section is empty.
Variables ¶
var AttrReader = defaultAttrReader
AttrReader is called by have_attributes to read attribute `name` off actual. The default handles the built-in model; a host may replace it to dispatch to the interpreter. It returns (value, true) when the attribute exists.
var Predicate = defaultPredicate
Predicate is called by predicate matchers (be_empty → empty?) to evaluate the predicate method on actual, returning (result, ok) where ok is false when the object does not respond to the predicate. The default handles the built-in model; a host may replace it.
var Responder = defaultResponder
Responder is called by respond_to and predicate matchers to test whether actual answers to `method`. The default handles the built-in model and *Object.RespondsTo; a host may replace it.
Functions ¶
func BeWithin ¶
func BeWithin(delta float64) *beWithinMatcher
BeWithin builds be_within(delta); call Of to set the centre.
func ChangeObserved ¶
func ChangeObserved(obs Change) *changeMatcher
ChangeObserved builds a change matcher over a host-collected observation. Chain From/To/By/ByAtLeast/ByAtMost to constrain it.
func Expect ¶
Expect models `expect(actual).to(matcher)` / `.not_to(matcher)`. It returns the failure message (or "" on success) so the host can record a result without this package raising. Positive is the `to` direction.
func Inspect ¶
Inspect returns the Ruby `#inspect` of v, byte-faithful to MRI 4.0 for the value model this package supports. It is the string RSpec embeds in matcher and formatter messages.
func RespondTo ¶
func RespondTo(methods ...Symbol) *respondToMatcher
RespondTo matches when actual responds to every named method.
func TotalsLine ¶
TotalsLine reproduces RSpec's SummaryNotification#totals_line, e.g. "4 examples, 1 failure, 1 pending" with correct pluralisation, and an "N error(s) occurred outside of examples" clause when errors > 0.
Types ¶
type Change ¶
Change is the observation `change { probe }` collected around a block: the probe value before and after the host ran the example block. exprName is the source of the probe (e.g. "a[0]") used in the message.
type Describer ¶
type Describer interface {
Description() string
}
Describer is the optional protocol for a matcher's `description` (used by composed matchers and `all`, and by the documentation formatter's generated example names). Matchers that do not implement it fall back to a generic description.
type Example ¶
type Example struct {
Description string
Group *ExampleGroup
Focused bool
Skip bool // `xit` / skip: metadata — never runs
PendingMsg string // set when declared pending
Tags []string // metadata tag names (e.g. "slow", "focus")
Location string // "path:line" for the failed-examples rerun list
DefinedAt int // monotonic definition index for stable/seeded ordering
// Result fields, filled by the host after running the body.
Result Result
// contains filtered or unexported fields
}
Example is one `it`/`specify` example.
func OrderDefined ¶
OrderDefined returns the examples in definition order (RSpec's default).
func OrderRandom ¶
OrderRandom returns the examples shuffled by RSpec's seeded ordering. RSpec uses `Ordering::Random`, which shuffles with a Ruby MT-seeded RNG; here we use a deterministic Fisher-Yates driven by the same 32-bit seed so a given seed yields a stable, reproducible permutation (the ordering is deterministic, which is what the golden tests pin; exact parity with MRI's Mersenne Twister would require the host RNG).
func (*Example) FullDescription ¶
FullDescription is the space-joined chain of group descriptions plus the example description — RSpec's `full_description`, used by the documentation formatter's rerun/location line and doc labels.
type ExampleGroup ¶
type ExampleGroup struct {
Description string
Parent *ExampleGroup
Children []*ExampleGroup
Examples []*Example
Hooks []*Hook
Focused bool
Tags []string
}
ExampleGroup is a describe/context node in the tree.
func NewRootGroup ¶
func NewRootGroup(desc string) *ExampleGroup
NewRootGroup starts a top-level `RSpec.describe(desc)` group.
func (*ExampleGroup) AddHook ¶
func (g *ExampleGroup) AddHook(h *Hook)
AddHook attaches a hook/let/subject to the group.
func (*ExampleGroup) Describe ¶
func (g *ExampleGroup) Describe(desc string) *ExampleGroup
Describe adds a nested describe/context group.
func (*ExampleGroup) Focus ¶
func (g *ExampleGroup) Focus() *ExampleGroup
Focus marks the group focused (`fdescribe` / `:focus`).
func (*ExampleGroup) It ¶
func (g *ExampleGroup) It(desc string) *Example
It adds an example to the group and returns it for further metadata.
func (*ExampleGroup) SelectExamples ¶
func (g *ExampleGroup) SelectExamples(f Filter) []*Example
SelectExamples flattens the tree into the examples that should run under the filter, in definition order.
type Filter ¶
type Filter struct {
// IncludeTags, when non-empty, restricts to examples carrying any of them.
IncludeTags []string
// ExcludeTags drops examples carrying any of them.
ExcludeTags []string
// RunFocused, when true and any example is focused, restricts to focused
// examples (RSpec's default :focus filter). Detected automatically by
// SelectExamples when unset via anyFocused.
RunFocused bool
}
Filter selects which examples run given a filter. It applies :focus (when any example/group is focused, only focused ones run), inclusion tags, and exclusion tags, then flattens the tree in definition order. The returned examples carry the before/after chains the host must run around each.
type Hash ¶
type Hash struct {
// contains filtered or unexported fields
}
Hash is an insertion-ordered Ruby Hash. Go maps have no stable order, so the matchers and inspect use this to reproduce MRI's key order faithfully.
type Hook ¶
type Hook struct {
Kind HookKind
Scope HookScope
Name string // for let/subject: the memoized name
}
Hook is a before/after/around hook or a let/subject definition attached to a group. The body is the host's; this model records its kind and scope so the host runs them in RSpec's order.
type HookKind ¶
type HookKind int
HookKind distinguishes before/after/around and let/subject.
const ( // BeforeHook runs before an example (or the group for :context scope). BeforeHook HookKind = iota // AfterHook runs after. AfterHook // AroundHook wraps the example. AroundHook // LetDef is a lazy memoized helper (`let(:name) { … }`). LetDef // SubjectDef is the group's subject (`subject { … }` / `subject(:name)`). SubjectDef )
type Matcher ¶
type Matcher interface {
// Matches reports whether actual satisfies the matcher (RSpec `matches?`).
Matches(actual any) bool
// FailureMessage is rendered when a positive expectation (`to`) fails.
FailureMessage() string
// FailureMessageNegated is rendered when a negative expectation (`not_to`)
// fails (RSpec `failure_message_when_negated`).
FailureMessageNegated() string
}
Matcher is the RSpec matcher protocol as this package models it: a predicate on the actual value plus the two failure messages RSpec renders for `to` and `not_to`. It mirrors rspec-expectations' `matches?` / `failure_message` / `failure_message_when_negated`.
func BeGreaterOrEqual ¶
func BeGreaterThan ¶
Be returns a comparison builder; combine with a comparison operator via the Be* constructors below. Bare `be` (no operator) asserts truthiness like be_truthy but with its own message; RSpec's bare `be` is rarely used, so the operator forms are the common path.
func BeInstanceOf ¶
BeInstanceOf matches when actual's exact class is the named class.
func BeLessOrEqual ¶
func BeLessThan ¶
func BeNotEqualOp ¶
func BePredicate ¶
BePredicate builds a predicate matcher for `predicate?` (predicate given without the trailing '?'), e.g. BePredicate("empty") is be_empty.
func ContainExactly ¶
ContainExactly matches when actual holds exactly the given elements, any order.
func HaveAttributes ¶
HaveAttributes matches when actual's attributes equal the expected pairs.
func MatchArray ¶
MatchArray is contain_exactly with a single array argument.
func RaiseErrorObserved ¶
func RaiseErrorObserved(obs RaisedError, class string, message any) Matcher
RaiseErrorObserved builds a raise_error matcher over a host observation. class "" matches any error; message may be a string, *Regexp, or nil.
type Module ¶
type Module string
Module is a Ruby Module reference; inspect is the bare module name.
type Object ¶
type Object struct {
Class string
IVars map[string]any
Order []string
ID uint64 // object_id for equal? identity; 0 means "use pointer identity"
RespondsTo []string
}
Object is an opaque Ruby object of the given Class. RSpecClass reports the class name matchers such as be_a / be_instance_of test against; IVars and the object identity (ID) let the host reproduce `#<Class:0x…>` style inspects and have_attributes / respond_to reflection. RespondsTo lists the message names the object answers to (for respond_to and predicate matchers).
type RaisedError ¶
RaisedError is the host's observation of what an example block raised: the Ruby class name of the exception and its message, or Raised=false when the block completed normally.
type Range ¶
Range is a Ruby Range; inspect is `begin..end` (or `begin...end` when Exclusive), matching MRI.
type Reporter ¶
type Reporter struct {
// contains filtered or unexported fields
}
Reporter accumulates example results and renders the formatter output. It is driven by the host, which calls Example for each finished example in run order, then Summary once at the end.
func (*Reporter) Documentation ¶
Documentation renders the documentation-formatter tree: each group heading indented by depth, each example labelled with its outcome suffix.
func (*Reporter) Progress ¶
Progress renders the progress-formatter body (the run of `.`/`F`/`*` chars).
func (*Reporter) Render ¶
Render produces the full progress-formatter report (progress line, blank line, then the summary block) for the given timing — the common one-shot entry point mirroring `rspec`'s default output.
type Result ¶
type Result struct {
Status Status
// FailureMessage is the matcher's message (or exception text) on failure.
FailureMessage string
// FailureExpression is the source line RSpec prints after "Failure/Error:".
FailureExpression string
// PendingReason is shown for pending examples in the pending section.
PendingReason string
// ExceptionClass / backtrace are the host seam for errors; the formatter uses
// them when present but they are environment-specific, so tests focus on the
// deterministic message body.
ExceptionClass string
Backtrace []string
}
Result is the host-reported outcome of running an example body.
type Status ¶
type Status int
Status is an example's outcome, set by the host after it runs the body.
type Symbol ¶
type Symbol string
Symbol is a Ruby Symbol (`:name`). Its inspect is the leading-colon form.
type Timing ¶
type Timing struct {
// Text, when set, is used verbatim (the whole "X seconds (files took …)"
// clause). Otherwise Run/Load format the standard phrasing.
Text string
Run string // e.g. "0.01 seconds"
Load string // e.g. "0.03 seconds"
}
Timing is the caller-supplied timing for the "Finished in …" line. RSpec formats it as "Finished in X seconds (files took Y seconds to load)"; the host measures the durations, so a formatter renders whatever the host reports, keeping the rest of the output deterministic.
