Module: Speccify::Extension

Defined in:
lib/speccify.rb

Overview

Object

Instance Method Summary collapse

Instance Method Details

#def_matcher(matcher_name, &block) ⇒ Object

Custom matchers for (almost) FREE

A simple example first:

def_matcher :be_nil do |given, matcher, args|      
  given.nil?                                       
end                                                
nil.should be_nil

*provide def_matcher() the name of your matcher and attach a block that defines it’s behavior. *The return value of the block is a boolean that actually will be expected (should) or not expected (‘should_not`).

Three arguments are available inside the matcher block:

given

The object that has received the should or ‘should_not`.

matcher

The matcher object. You can set the failure messages as attributes on this object:

matcher.positive_msg = "You can see me if I am applied to should and I return a false value"
matcher.negative_msg = "You can see me if I am applied to should_not and I return a true value"

It holds a list of all methods that have been called on the matcher (for chaining):

obj.should matcher_name.some_method(4,5,6) {"and a block"}.second                                              
def_matcher :matcher_name do |given, matcher, args|                                                            
  # this is an ostruct that holds all information about the first method 'some_method'                         
  matcher.msgs[0]                                                                                              
  # this is an ostruct that holds all information about the second method 'second'                             
  matcher.msgs[1]                                                                                              
  # this is the name of the first method:                                                                      
  matcher.msgs[0].name  #=> :some_method                                                                       
  # this is a list of arguments that have been passed to the first method:                                     
  matcher.msgs[0].args  #=> [4,5,6]                                                                            
  # this is the block that was attached:                                                                       
  matcher.msgs[0].block #=> proc {"and a block"}                                                               
end

args

A list of all arguments that have been applied to the matcher. Like the 6 in:

(3*3).should_not be(6)


234
235
236
237
238
# File 'lib/speccify.rb', line 234

def def_matcher(matcher_name, &block)
  self.class.send :define_method, matcher_name do |*args|
    Speccify::Functions::build_matcher(matcher_name, args, &block)
  end
end