Andy Pearson
2007-Dec-09 19:54 UTC
[rspec-users] Writing Specifications for Custom Form Builders (and Helpers)
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.concat(@template.content_tag(:div, @template.capture(&block)), block.binding) end end 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 like: 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 object'' it ''should not return the error message if there are no errors on the object'' end 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! Andy