[rspec-users] problems matching generated html output...

Patrick J. Collins patrick at collinatorstudios.com
Thu Nov 3 18:36:59 EDT 2011

So, I am writing tests for a presenter class that outputs html markup.

I have a method that does something like this:

def output

  things.map do |thing|

    content_tag :div, :id => thing[:id] do
	   [content_tag :p, thing[:body_1],
		 content_tag :p, thing[:body_2].join.html_safe




Then my spec is something like this:

  it "returns markup" do

	@presenter.stubs(:things).returns({:id => "an_id", :body_1 => "hello",
	 :body_2 => "goodbye"})

   @presenter.output.should == filter_for_html("

		<div id="an_id">

and I made this filter_for_html helper method which allows me to not care about
whitespace...  So that just does:

  def filter_for_html(markup)
    markup.squeeze(" ").strip.gsub(/\n\s+/, "")

And this effctively strips out all the whitespace and gives me a string like:
"<div id="an_id"><p>hello</p><p>goodbye</p></div>"



Now for my question--- I have two problems and am not sure what the best to
solve either one is:

1)  The match fails because content_tag apparently inserts in a few \n's here
and there.

2)  My background explanation was actually quite simplified, and my presenter
class is actually rendering some haml partials, and something like %ul.foo
turns into <ul class='foo'>  (note the SINGLE QUOTES)..  So my test fails
because my expectation code uses double classes

3)  Some of the text generated via the partials is calling things like
.humanize which capitalize text and I am not really concerned about those
details in my test..........

So the way I got my test passing is to do:

@presenter.output.gsub("\n", "").gsub("'", "\"").downcase.should == filter_for_html(' ... same content as before ... ')

Which I don't know about you, but that makes me go "ewwwwwwwwww".  And makes
all the RSpec readibility go out the window.  Is there something I should be
doing with a custom matcher or something to test for case-indifferent text,
ignore whitespace and \n, and be quote indifferent?


Patrick J. Collins

More information about the rspec-users mailing list