[rspec-users] Writing Specifications for Custom Form Builders (and Helpers)

Andy Pearson andypearson at criticalwebdesign.co.uk
Sun Dec 9 14:54:59 EST 2007

Hello all,

Long time reader, first time poster!

I am a relative newcomer (no idea what on earth I am doing) to Ruby,  
Rails and Rspec and have a feeling I am probably trying to run before  
I know how to walk.

I had imagined a cool way of outputting a div around some form stuff  
which would have a class on it if the related field had errors,  
something a bit like:

<% f.div_with_errors_for :login do %>
	<label for="user_login">Login Name:</label>
	<%= f.text_field :login %>
<% end %>

It will output a regular div if there are no errors on the field or  
<div class="error">... if there is an error.

So, I began trying to get this working. Searching about I discovered  
that I could create a custom form builder so i created lib/ 
extended_form_builder.rb along with spec/lib/ 
extended_form_builder_spec.rb so I could start writing my  
specifications. So far, so good.

An hour or so later, after searching, reading Rails source code and  
abandoning specs completely I have ended up with the very basic:

class ExtendedFormBuilder < ActionView::Helpers::FormBuilder

   def div_with_errors_for(object_name, &block)
@template.capture(&block)), block.binding)


Which only wraps the block I pass to it with a <div> and outputs it  
correctly using erb. The problem is, I have NO specs for it, and I  
don't want to continue writing the rest of the method until I know how  
to spec it correctly.

Any tips on how I should be speccing this, I guess I need to stub out  
@template correctly (?!) as at the moment, the  
extended_form_builder_spec.rb is not running like a view spec where I  
assume @template would be set up.

Which brings me onto my second question, what sort of tone of voice  
should I be using to describe Helpers, at the moment I am using stuff  

describe ApplicationHelper, 'error_message_for method' do

   it 'should not return the error message if the instance doesnt  
exist yet'
   it 'should return the error message if there are errors on the  
   it 'should not return the error message if there are no errors on  
the object'


But it doesn't feel right, I guess it isn't "real" enough, too much  
talk of methods and objects I suppose.

Thanks for taking the time to read this, and thanks in advance for any  
advice you can offer!


More information about the rspec-users mailing list