labs rails ruby testing

Testing Custom Form Builders in Rails

Rails gives you the ability to customize the output when using the form_for view helper in a view by using a custom form builder. This functionality is great if you want to change the default HTML generated by the form_for view helper.

Figuring out how to test your custom form builder is not so easy. In order to instantiate a form builder, you need a template object. This object is typically the view that is getting rendered but if you are trying to unit test your custom form builder, you don’t necessarily have one of those laying around. The easiest way to make one is to extend a plain, old Ruby object with a couple of ActionView modules:

@template = Object.new
@template.extend ActionView::Helpers::FormHelper
@template.extend ActionView::Helpers::FormOptionsHelper

You can then use this object as the template in your tests:

foo = Foo.new
form_builder = FooEditFormBuilder.new(:foo, foo, @template, {})
# Your tests go here