Class: RSpec::Maybes::MaybeTarget

Inherits:
Object
  • Object
show all
Defined in:
lib/rspec/maybes/maybe_target.rb

Overview

Note:

`MaybeTarget` is not intended to be instantiated directly by users. Use `maybe` instead.

Wraps the target of a maybe.

Examples:

maybe(something)       # => MaybeTarget wrapping something
maybe { do_something } # => MaybeTarget wrapping the block

# used with `will`
maybe(actual).will eq(3)

# with `will_not`
maybe(actual).will_not eq(3)

Direct Known Subclasses

BlockMaybeTarget

Constant Summary collapse

UndefinedValue =

Used as a sentinel value to be able to tell when the user did not pass an argument. We can't use `nil` for that because `nil` is a valid value to pass.

Module.new

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ MaybeTarget

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of MaybeTarget.


27
28
29
# File 'lib/rspec/maybes/maybe_target.rb', line 27

def initialize(value)
  @target = value
end

Class Method Details

.for(value, block) ⇒ Object


32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rspec/maybes/maybe_target.rb', line 32

def self.for(value, block)
  if UndefinedValue.equal?(value)
    unless block
      raise ArgumentError, "You must pass either an argument or a block to `maybe`."
    end
    BlockMaybeTarget.new(block)
  elsif block
    raise ArgumentError, "You cannot pass both an argument and a block to `maybe`."
  else
    new(value)
  end
end

Instance Method Details

#will(matcher = nil, message = nil, &block) ⇒ Boolean

Runs the given maybe, passing randomly.

Examples:

maybe(value).will eq(5)
maybe { perform }.will_not raise_error

Parameters:

  • matcher (Matcher) (defaults to: nil)
  • message (String or Proc) (defaults to: nil)

    optional message to display when the expectation fails

Returns:

  • (Boolean)

    true if the maybe succeeds (else raises)

See Also:

  • RSpec::Matchers

54
55
56
57
# File 'lib/rspec/maybes/maybe_target.rb', line 54

def will(matcher = nil, message = nil, &block)
  prevent_operator_matchers(:will) unless matcher
  RSpec::Maybes::PositiveMaybeHandler.handle_matcher(@target, matcher, message, &block)
end

#will_not(matcher = nil, message = nil, &block) ⇒ Boolean

Runs the given maybe, failing randomly.

Examples:

maybe(value).will_not eq(5)

Parameters:

  • matcher (Matcher) (defaults to: nil)
  • message (String or Proc) (defaults to: nil)

    optional message to display when the maybe fails

Returns:

  • (Boolean)

    false if the negative maybe succeeds (else raises)

See Also:

  • RSpec::Matchers

67
68
69
70
# File 'lib/rspec/maybes/maybe_target.rb', line 67

def will_not(matcher = nil, message = nil, &block)
  prevent_operator_matchers(:will_not) unless matcher
  RSpec::Maybes::NegativeMaybeHandler.handle_matcher(@target, matcher, message, &block)
end