#Provides some helper methods for modifying xml (as plain text). (removing and replacing nodes) #so far, this module knows nothing about libxml, only about xml (and very roughly) #This is intended for inclusion in Test::Unit::TestCase. #If you're not mixing it in to such a context, #note that it will need the assertions definitions to work: #require 'test/unit/assertions' #include Test::Unit::Assertions module LibXMLTestHelper #from given xml snippet str, removes first encountered node with the given name. #e.g. ALL of FIRST title AND nested in the following #text here<n>other stuff</n>this one untouched... def remove_first_node_called(name, original_xml) return remove_nodes_called(name, original_xml, true) end #from given xml snippet str, removes either first node or all nodes encountered with the given name. def remove_nodes_called(name, original_xml, limit_to_first = false) new_xml = replace_nodes_called(name, original_xml, '', limit_to_first) assert_not_equal original_xml.gsub(/\n\w*/,''), new_xml.gsub(/\n\w*/,''), "shouldn't be equal - should have stripped '#{name}' tag" return new_xml end #from given xml snippet str, replaces the first node with the given name, with the given contents. def replace_first_node_called(name, original_xml, replacement_string) replace_nodes_called(name, original_xml, replacement_string, true) end #from given xml snippet str, replaces either first node or all nodes encountered (of the given name) with the given contents. def replace_nodes_called(name, original_xml, replacement_string, limit_to_first = false) operation = limit_to_first ? :sub : :gsub assert_not_nil original_xml, 'given nil for original xml to work with' new_xml = original_xml.send(operation, /<#{name}.*?<\/#{name}>/m,replacement_string)#m is multiline. #*? is don't be greedy or we'll get more than first. assert_not_equal original_xml.gsub(/\n\w*/,''), new_xml.gsub(/\n\w*/,''), "shouldn't be equal - should have replaced '#{name}' tag with #{replacement_string}" assert_not_nil new_xml, 'substitution returned nil - something went wrong' return new_xml end end