Testing Custom Form Builders in Rails

October 28, 2013 Mike Gehard

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

 

About the Author

Biography

More Content by Mike Gehard
Previous
Improved Java Tooling for Cloud Foundry
Improved Java Tooling for Cloud Foundry

Pivotal has released several new components that enable developers using Java, Groovy, and other JVM langua...

Next
Why You Should Give Your Mobile App as Much Attention as Your Smallest Store
Why You Should Give Your Mobile App as Much Attention as Your Smallest Store

This blog originally appeared on The Mobile Retail Blog.   Your mobile app reaches more customers than your...

Enter curious. Exit smarter.

Learn More