Module: RSpec::Maybes

Defined in:
lib/rspec/maybes.rb,
lib/rspec/maybes/syntax.rb,
lib/rspec/maybes/version.rb,
lib/rspec/maybes/handlers.rb,
lib/rspec/maybes/fail_with.rb,
lib/rspec/maybes/maybe_target.rb

Overview

RSpec::Maybes provides a simple, readable API to express possible outcomes in a code example. To express an potential outcome, wrap an object or block in `maybe`, call `will` or `will_not` and pass it a matcher object:

maybe(order.total).will eq(Money.new(5.55, :USD))
maybe(list).will include(user)
maybe(message).will_not match(/foo/)
maybe { do_something }.will raise_error

The last form (the block form) is needed to match against ruby constructs that are not objects, but can only be observed when executing a block of code. This includes raising errors, throwing symbols, yielding, and changing values.

When `maybe(…).will` is invoked with a matcher, it turns around and calls `matcher.matches?(<object wrapped by maybe>)`. For example, in the expression:

maybe(order.total).will eq(Money.new(5.55, :USD))

…`eq(Money.new(5.55, :USD))` returns a matcher object, and it results in the equivalent of `eq.matches?(order.total)`. If `matches?` happens to return `true`, the expectation is met and execution continues. If `false`, then the spec fails with the message returned by `eq.failure_message`.

Given the expression:

maybe(order.entries).will_not include(entry)

… pretty much the same thing happens. `will_not` is simply an alias of `will`. It's random!

spec-me-maybe ships with the same standard set of useful matchers as rspec-expectations does, and writing your own matchers is quite simple.

Defined Under Namespace

Modules: MaybeHelper, Syntax Classes: BlockMaybeTarget, MaybeHandler, MaybeTarget, NegativeMaybeHandler, PositiveMaybeHandler, Version

Constant Summary collapse

MaybeNot =
Note:

We subclass Exception so that in a stub implementation if

Exception raised when a maybe fails.

the user sets an expectation, it can't be caught in their code by a bare `rescue`.

Class.new(::RSpec::Expectations::ExpectationNotMetError)
VERSION =
Version.to_s

Class Method Summary collapse

Class Method Details

.fail_with(message, failure_message_method) ⇒ Object

Raises an RSpec::Maybes::MaybeNot with message. Adds a diff to the failure message when `expected` and `actual` are both present.

Parameters:

  • message (String)

Raises:


9
10
11
12
13
14
15
16
17
18
# File 'lib/rspec/maybes/fail_with.rb', line 9

def fail_with(message, failure_message_method)
  unless message
    raise ArgumentError, "Failure message is nil. Does your matcher define the " \
                         "appropriate failure_message[_when_negated] method to return a string?"
  end

  message = "#{message} Maybe next time, though?"

  raise RSpec::Maybes::MaybeNot, message
end