Class: EqualElementMatcher

Inherits:
Object show all
Defined in:
lib/mspec/matchers/equal_element.rb

Instance Method Summary collapse

Constructor Details

#initialize(element, attributes = nil, content = nil, options = {}) ⇒ EqualElementMatcher

Returns a new instance of EqualElementMatcher.



2
3
4
5
6
7
# File 'lib/mspec/matchers/equal_element.rb', line 2

def initialize(element, attributes = nil, content = nil, options = {})
  @element = element
  @attributes = attributes
  @content = content
  @options = options
end

Instance Method Details

#attributes_for_failure_messageObject



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/mspec/matchers/equal_element.rb', line 49

def attributes_for_failure_message
  if @attributes
    if @attributes.empty?
      "no attributes"
    else
      @attributes.inject([]) { |memo, n| memo << %Q{#{n[0]}="#{n[1]}"} }.join(" ")
    end
  else
    "any attributes"
  end
end

#content_for_failure_messageObject



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/mspec/matchers/equal_element.rb', line 61

def content_for_failure_message
  if @content
    if @content.empty?
      "no content"
    else  
      "#{@content.inspect} as content"
    end
  else
    "any content"
  end
end

#failure_messageObject



39
40
41
42
# File 'lib/mspec/matchers/equal_element.rb', line 39

def failure_message
  ["Expected #{@actual.pretty_inspect}",
   "to be a '#{@element}' element with #{attributes_for_failure_message} and #{content_for_failure_message}"]
end

#matches?(actual) ⇒ Boolean

Returns:

  • (Boolean)


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mspec/matchers/equal_element.rb', line 9

def matches?(actual)
  @actual = actual
  
  matched = true
  
  if @options[:not_closed]
    matched &&= actual =~ /^#{Regexp.quote("<" + @element)}.*#{Regexp.quote(">" + (@content || ''))}$/
  else
    matched &&= actual =~ /^#{Regexp.quote("<" + @element)}/
    matched &&= actual =~ /#{Regexp.quote("</" + @element + ">")}$/
    matched &&= actual =~ /#{Regexp.quote(">" + @content + "</")}/ if @content      
  end
  
  if @attributes
    if @attributes.empty?
      matched &&= actual.scan(/\w+\=\"(.*)\"/).size == 0
    else
      @attributes.each do |key, value|
        if value == true
          matched &&= (actual.scan(/#{Regexp.quote(key)}(\s|>)/).size == 1)
        else
          matched &&= (actual.scan(%Q{ #{key}="#{value}"}).size == 1)
        end
      end        
    end
  end
  
  !!matched
end

#negative_failure_messageObject



44
45
46
47
# File 'lib/mspec/matchers/equal_element.rb', line 44

def negative_failure_message
  ["Expected #{@actual.pretty_inspect}",
    "not to be a '#{@element}' element with #{attributes_for_failure_message} and #{content_for_failure_message}"]
end