Class: MiniSpec::Mocks::Stub

Inherits:
Object
  • Object
show all
Defined in:
lib/minispec/mocks/stubs.rb

Instance Method Summary collapse

Constructor Details

#initialize(object, messages, stubs = {}) ⇒ Stub

Returns a new instance of Stub.



21
22
23
# File 'lib/minispec/mocks/stubs.rb', line 21

def initialize object, messages, stubs = {}
  @object, @messages, @stubs, @blocks = object, messages, stubs, {}
end

Instance Method Details

#most_relevant_block_for(args) ⇒ Object



82
83
84
# File 'lib/minispec/mocks/stubs.rb', line 82

def most_relevant_block_for args
  @blocks[args] || @catchall_block || proc {}
end

#stubify(stub, visibility, &block) ⇒ Object

defines given stub of given visibility on ‘@object`

Parameters:

  • stub
    • when stub is a symbol it defines a method. if ‘@object` has a singleton method with stub name or the stub name is :nil?, the method are defined using `define_singleton_method`. otherwise `@object` are extended with a module containing needed methods(@see #mixin)

    • when given stub contain dots, a chained stub defined(@see #define_chained_stub)

  • visibility

    stub visibility, :public(default), :protected, :private

  • &proc (Proc)

    block to be yielded when stub called

Raises:

  • ArgumentError if given stub is not a Symbol, String, Hash or Array



72
73
74
75
76
77
78
79
80
# File 'lib/minispec/mocks/stubs.rb', line 72

def stubify stub, visibility, &block
  stub.is_a?(Symbol) || raise('stubs names should be provided as symbols')

  @catchall_block = block if block # IMPORTANT! update catchall block only if another block given

  @object.singleton_methods.include?(stub) || stub == :nil? ?
    define_singleton_stub(stub) :
    define_regular_stub(stub, visibility)
end

#with(*args, &block) ⇒ Object

makes a stub to behave differently depending on given arguments

Examples:

stub(a, :b).
  with(1) { :one }. # `a.b(1)` will return :one
  with(2) { :two }  # `a.b(2)` will return :two


32
33
34
35
# File 'lib/minispec/mocks/stubs.rb', line 32

def with *args, &block
  @blocks[args] = block || proc {}
  self
end

#with_any(*args, &block) ⇒ Object Also known as: any

defines a catchall block

Examples:

with a block

stub(a, :b).
  with(1)  { :one }. # `a.b(1)` will return :one
  with_any { :any }  # `a.b(:any_args, :or_no_args)` will return :any

with a value

stub(a, :b).
  with(1) { :one }.
  with_any(:any)


49
50
51
52
53
54
55
56
57
# File 'lib/minispec/mocks/stubs.rb', line 49

def with_any *args, &block
  # this args mangling needed to be able to accept nil or false as value
  (value_given = args.size == 1) || args.size == 0 ||
    raise(ArgumentError, 'Wrong number of arguments, %i instead of 0..1' % args.size)
  value_given && block && raise(ArgumentError, 'Both a value and a block used. Please use either one')
  value_given || block || raise(ArgumentError, 'No value nor block provided')
  @catchall_block = value_given ? proc { args.first } : block
  self
end