Class: Spec::HaveHelper

Inherits:
ShouldBase show all
Defined in:
lib/spec/api/helper/have_helper.rb

Instance Method Summary collapse

Methods inherited from ShouldBase

#default_message, #diff_as_string, #fail_with_message, #old_default_message

Constructor Details

#initialize(target, relativity = :exactly, expected = nil) ⇒ HaveHelper

Returns a new instance of HaveHelper.



5
6
7
8
9
10
# File 'lib/spec/api/helper/have_helper.rb', line 5

def initialize(target, relativity=:exactly, expected=nil)
  @target = target
  @expected = expected == :no ? 0 : expected
  @at_least = (relativity == :at_least)
  @at_most = (relativity == :at_most)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args) ⇒ Object



12
13
14
# File 'lib/spec/api/helper/have_helper.rb', line 12

def method_missing(sym, *args)
  fail_with_message(build_message(sym)) unless as_specified?(sym)
end

Instance Method Details

#actual_size(collection) ⇒ Object



20
21
22
23
# File 'lib/spec/api/helper/have_helper.rb', line 20

def actual_size(collection)
  return collection.length if collection.respond_to? :length
  return collection.size if collection.respond_to? :size
end

#as_specified?(sym) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
35
36
# File 'lib/spec/api/helper/have_helper.rb', line 32

def as_specified?(sym)
  return actual_size(collection(sym)) >= @expected if @at_least
  return actual_size(collection(sym)) <= @expected if @at_most
  return actual_size(collection(sym)) == @expected
end

#build_message(sym) ⇒ Object



25
26
27
28
29
30
# File 'lib/spec/api/helper/have_helper.rb', line 25

def build_message(sym)
  message = "<#{@target.class.to_s}> should have"
  message += " at least" if @at_least
  message += " at most" if @at_most
  message += " #{@expected} #{sym} (has #{actual_size(collection(sym))})"
end

#collection(sym) ⇒ Object



16
17
18
# File 'lib/spec/api/helper/have_helper.rb', line 16

def collection(sym)
  @target.send(sym)
end