require 'minitest/autorun'
require 'nokogiri'
require_relative '../lib/devcenter-parser/header_id_generator'
describe 'HeaderIdGeneratorTest' do
it 'respects existing ids in non-header elements' do
html = 'clean'
assert_equal html, result(html)
end
it 'inserts ids in subheaders' do
html = '
Foo Bar Header 123
'
assert_id result(html), 'h2', 'foo-bar-header-123'
end
it 'generates ids replacing inner non-alphanum chars with dashes' do
['Foo Bar', 'Foo-Bar', 'Foo#bar', 'Foo##Bar', 'Foo##Bar', '-$Foo##Bar$-'].each do |title|
html = "#{title}
"
assert_id result(html), 'h2', 'foo-bar'
end
end
describe 'ensures that there are not collisions between ids in subheaders' do
describe 'by prepending the id of the previous headers as long as necessary' do
it 'when there are conflicts on headers from different sections' do
html = <<-HTML
A
B
Z
C
B
Z
HTML
result = result(html)
%w{ a c }.each{ |id| assert_id(result, 'h2', id) }
%w{ a-b c-b }.each{ |id| assert_id(result, 'h3', id) }
%w{ a-b-z c-b-z }.each{ |id| assert_id(result, 'h4', id) }
end
it 'when there are conflicts on headers from different sections where some headers are missing' do
html = <<-HTML
A
Z
C
Z
HTML
result = result(html)
%w{ a c }.each{ |id| assert_id(result, 'h2', id) }
%w{ c-z }.each{ |id| assert_id(result, 'h3', id) }
%w{ a-z }.each{ |id| assert_id(result, 'h4', id) }
end
it 'when there are conflicts inside the same section' do
html = <<-HTML
D
X
Z
Y
Z
HTML
result = result(html)
%w{ d }.each{ |id| assert_id(result, 'h2', id) }
%w{ x y }.each{ |id| assert_id(result, 'h3', id) }
%w{ x-z y-z }.each{ |id| assert_id(result, 'h4', id) }
end
end
it 'by appending numbers for those subheaders with same nesting level and parent header name' do
html = <<-HTML
A
B
B
C
C
HTML
result = result(html)
%w{ a c-1 c-2 }.each{ |id| assert_id(result, 'h2', id) }
%w{ a-b-1 a-b-2 }.each{ |id| assert_id(result, 'h3', id) }
end
end
def assert_id(html, tag, id)
assert html.include?("<#{tag} id=\"#{id}\">"), "<#{tag} id=\"#{id}\"> not found"
end
def result(html)
doc = Nokogiri::HTML::DocumentFragment.parse(html)
HeaderIdGenerator.new(doc)
doc.to_html
end
end