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

Matt Wynne matt at mattwynne.net
Thu Nov 3 19:07:19 EDT 2011


On 3 Nov 2011, at 22:36, Patrick J. Collins wrote:

> 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
> 	 end
> 
>  end.join.html_safe
> 
> end
> 
> ...
> 
> 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">
> 			<p>hello</p>
> 			<p>goodbye</p>
> 	   </div>
> 	 ")
>  end
> 
> 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+/, "")
>  end
> 
> 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>"
> 
> ...
> 
> -- END OF BACKGROUND EXPLANATION --
> 
> 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?
> 
> Thanks.
> 
> Patrick J. Collins
> http://collinatorstudios.com

I realise this isn't the answer you're looking for, but I'm curious: where did you get the idea that a presenter should know anything about HTML?

cheers,
Matt

--
Freelance programmer & coach
Author, http://pragprog.com/book/hwcuc/the-cucumber-book (with Aslak Hellesøy)
Founder, http://relishapp.com
+44(0)7974430184 | http://twitter.com/mattwynne



More information about the rspec-users mailing list