Sha256: 8cdc295386a7fac08259a2d9878b3a7cabff57abd2b4d98042b29b0f8a8a6524

Contents?: true

Size: 1.95 KB

Versions: 6

Compression:

Stored size: 1.95 KB

Contents

require 'test/unit'

class Test::Unit::TestCase

  # Split an (X)HTML tag into its constituent parts, e.g. tag name, tag attributes (if any),
  # and tag content (if any).  We are assuming that we are being given a valid XHTML tag (i.e
  # all attributes have both a name and a value, and that value is enclosed in double quotes).
  # Returns a hash:
  #   { :name => 'tag_name', :attributes => {'attribute1' => 'value1', ...}, :content => 'text content' } 
  def split_html_tag(tag)
    # Rather then try to come up with some big huge regexp that matches every bit of
    # the tag, let's just easily match each part.

    # Match the tag name
    name_match = /<(\w+)/.match(tag)
    name = (name_match.nil? ? nil : name_match[1])
    
    # Match the tag content
    content_match = /<.+>(.*)<\/.+>/.match(tag)
    content = (content_match.nil? ? nil : content_match[1])
    
    # Match _all_ the key => value attribute pairs
    attributes = {}
    rest_of_tag = tag
    while (attribute_match = /(\w+)="([^"]+)"/.match(rest_of_tag))
      attributes[attribute_match[1]] = attribute_match[2]
      rest_of_tag = attribute_match.post_match
    end
    
    {:name => name, :attributes => attributes, :content => content}
  end

  # Asserts that two html tags match each other.  In this case 'matching' means that they have
  # the same name, same attributes (which can be in any order) and the same content (if any).
  # Note: this does not check tags for well-formedness.
  def assert_tags_match(tag_one, tag_two, message = nil)
    message = build_message message, 'Tag <?> does not match <?>.', tag_one, tag_two
    assert_block message do
      split_tag_one = split_html_tag(tag_one)
      split_tag_two = split_html_tag(tag_two)

      (split_tag_one[:name] === split_tag_two[:name]) &&
        (split_tag_one[:attributes] === split_tag_two[:attributes]) &&
        (split_tag_one[:content] === split_tag_two[:content])
    end
  end
  
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
staticmatic-0.9.0 test/test_helper.rb
staticmatic-0.8.10 test/test_helper.rb
staticmatic-0.9.1 test/test_helper.rb
staticmatic-0.9.4 test/test_helper.rb
staticmatic-0.9.3 test/test_helper.rb
staticmatic-0.9.5 test/test_helper.rb