[英]How do I test a Formtastic custom input with rspec?
我有一個rubygem定義了一個自定義的SemanticFormBuilder類,它添加了一個新的Formtastic輸入類型。 代碼按預期工作,但我無法弄清楚如何為它添加測試。 我以為我可以做一些像加載Formtastic,調用semantic_form_for,然后使用我的自定義的廣告輸入:as
類型,但我不知道從哪里開始。
有誰知道任何做這樣的事情的寶石,我可以看一下這個來源? 有關從哪里開始的任何建議?
我的寶石需要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找到
我們的團隊在這種方法上取得了成功,我認為我們最初是從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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.