How to test Formtastic user input with rspec?

I have a rubygem that defines its own SemanticFormBuilder class that adds a new Formtastic input type. The code works as expected, but I cannot figure out how to add tests to it. I thought I could do something like loading Formtastic, call semantic_form_for, and then entering an ad using my own type :as , but I have no idea where to start.

Does anyone know of any gems that do something similar so that I can take a look at the source? Any suggestions on where to start?

My gem requires Rails 2.3.x

The source for my user input looks like this, and I include it in the initializer in my application:

 module ClassyEnumHelper class SemanticFormBuilder < Formtastic::SemanticFormBuilder def enum_select_input(method, options) enum_class = object.send(method) unless enum_class.respond_to? :base_class raise "#{method} does not refer to a defined ClassyEnum object" end options[:collection] = enum_class.base_class.all_with_name options[:selected] = enum_class.to_s select_input(method, options) end end end 

Not sure if any of my other source codes will help, but it can be found here http://github.com/beerlington/classy_enum

+4
source share
1 answer

Testing your output

Our team was successful in this approach, which, it seems to me, was originally borrowed from our own Formtastic tests.

First create a buffer to capture the output you want to test.

 # spec/support/spec_output_buffer.rb class SpecOutputBuffer attr_reader :output def initialize @output = ''.html_safe end def concat(value) @output << value.html_safe end end 

Then call semantic_form_for in your test, capturing the output in the buffer. Once you do this, you can verify that the result was what you expected.

Here is an example when I redefined StringInput to add a CSS integer class to the inputs for integer model properties.

 # spec/inputs/string_input_spec.rb require 'spec_helper' describe 'StringInput' do # Make view helper methods available, like `semantic_for_for` include RSpec::Rails::HelperExampleGroup describe "classes for JS hooks" do before :all do @mothra = Mothra.new end before :each do @buffer = SpecOutputBuffer.new @buffer.concat(helper.semantic_form_for(@mothra, :url => '', as: 'monster') do |builder| builder.input(:legs).html_safe + builder.input(:girth).html_safe end) end it "should put an 'integer' class on integer inputs" do @buffer.output.should have_selector('form input#monster_legs.integer') end end end 
+3
source

All Articles