【问题标题】:How do I test a Formtastic custom input with rspec?如何使用 rspec 测试 Formtastic 自定义输入?
【发布时间】:2010-10-04 22:14:37
【问题描述】:

我有一个 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

【问题讨论】:

    标签: ruby-on-rails testing rubygems rspec formtastic


    【解决方案1】:

    测试你的输出

    我们的团队在这种方法上取得了成功,我认为我们最初是从 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 以将 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
    

    【讨论】:

    • 我不确定这个答案是否仍然有效,我似乎一直在遇到 ` '_routes' is not available from within an example (e.g. an 'it' block) or from constructors that run in示例的范围(例如“之前”、“让”等)。它仅在示例组中可用(例如“描述”或“上下文”块)。`也很可能是我正在做一些事情。
    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多