代码之家  ›  专栏  ›  技术社区  ›  Peter Brown

如何使用rspec测试Formtastic自定义输入?

  •  4
  • Peter Brown  · 技术社区  · 14 年前

    我有一个rubygem,它定义了一个自定义的SemanticFormBuilder类,它添加了一个新的Formtastic输入类型。代码按预期工作,但我不知道如何为它添加测试。我在想我可以做一些事情,比如加载Formtastic,调用semantic\u form\u,然后使用我的自定义输入 :as

    我的gem需要rails2.3.x

    自定义输入的源代码如下所示,我将其包含在应用程序的初始值设定项中:

    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
    

    不确定我的其他源代码是否有用,但可以在这里找到 http://github.com/beerlington/classy_enum

    1 回复  |  直到 14 年前
        1
  •  3
  •   Nathan Long    12 年前

    测试输出

    # 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
    

    那就打电话 semantic_form_for 在测试中,将输出捕获到缓冲区。一旦完成了,就可以测试输出是否符合预期。

    integer CSS类来输入整数模型属性。

    # 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