4

我有一个 ruby​​gem,它定义了一个自定义 SemanticFormBuilder 类,它添加了一个新的 Formtastic 输入类型。该代码按预期工作,但我不知道如何为其添加测试。我在想我可以做一些事情,比如加载 Formtastic,调用 semantic_form_for,然后添加使用我的自定义:as类型的输入,但我不知道从哪里开始。

有谁知道有什么宝石可以做这样的事情,我可以看看它的来源?关于从哪里开始的任何建议?

我的 gem 需要 Rails 2.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

4

1 回答 1

3

测试你的输出

我们的团队在这种方法上取得了成功,我认为我们最初是从 Formtastic 自己的测试中借用的。

首先,创建一个缓冲区来捕获您要测试的输出。

# 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您的测试,将输出捕获到您的缓冲区。完成后,您可以测试输出是否符合您的预期。

这是一个示例,其中我覆盖了 StringInput 以将integerCSS 类添加到整数模型属性的输入。

# 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
于 2012-05-15T19:59:55.267 回答