Spec a FormBuilder in RSpec

yesterday, I started trying to work on a helper for generating a frequently-repeated calendar widget for the rails app at $WORK. Being the good BDDer that I am, I launched off a new spec to test the form builder — and to attempt to backfill specs and cover up the evidence of my naughty non-testing past.

This is a form builder we use in a couple of heavily used forms on the site, so we “know” this works, aside from the new code I want to add. But in moving in to backfill some specs, I discovered that, like many things relating to form builders in rails, it’s not the easiest thing to do, nor is it exactly well documented …

After a bit of digging, I finally managed to work out the right setup to get this going. Documented below for posterity

# spec/helper/random_form_builder_spec.rb
  describe RandomFormBuilder do
    attr_reader :builder, :helper
    before do
      @helper = Object.extend(ActionView::Helpers::FormHelper)
      @object = stub_model(Random)
      @builder = RandomFormBuilder.new(:random, @object, @helper, {}, nil)
    end
  end

You can then spec as normal, calling methods on builder and verifying the result.

The tricky part is the constructor.

:random
This is the name of the object, by analog, the first argument of a #form_for
@object
The object you run with; where the form pulls field values from
@helper
this is the tricky one. A form builder is really just a pass-through, decorating calls down to methods that live in FormHelper. If you don’t have a template that defines the FormHelper methods, failures abound.

{}
Options for the FormBuilder. Here, unused
nil
A proc

2 Responses to “Spec a FormBuilder in RSpec”


Leave a Reply