How to test custom inputs?

已查看 57 次
跳至第一个未读帖子

Tanguy Krotoff

未读,
2012年4月30日 08:14:172012/4/30
收件人 plataformate...@googlegroups.com
Hi,

I have written a custom input for simple_form and I would like to know how to (unit) test it.
I'm reading simple_form source code to see how tests work but it is a bit cryptic for me.

I guess a good example inside simple_form documentation would be a nice addition.

Regards,

Tanguy Krotoff

未读,
2012年4月30日 08:52:222012/4/30
收件人 plataformate...@googlegroups.com
Jumping into the code is the way of the Jedi :)

Here how I do it:

# Here my custom input
# File app/inputs/date_pair_input.rb
class DatePairInput < SimpleForm::Inputs::Base
  def input
    [...]
  end
end

# My unit test for my custom input
# File test/unit/inputs/date_pair_input_test.rb
class MyInputTest < ActionView::TestCase
  include SimpleForm::ActionViewExtensions::FormHelper

  # Taken from simple_form/test/support/misc_helpers.rb
  def with_concat_form_for(*args, &block)
    concat simple_form_for(*args, &(block || proc {}))
  end

  # Taken from simple_form/test/support/misc_helpers.rb
  def with_input_for(object, attribute_name, type, options={})
    with_concat_form_for(object) do |f|
      f.input(attribute_name, options.merge(:as => type))
    end
  end

  test "MyInput" do
    # This is my model
    event = Event.new
    event.title = 'My event title'
    event.starts_at = Time.new(2012, 02, 15, 23, 21)
    event.ends_at = event.starts_at + 1.hour

    # Test the text input that comes built-in with simple_form
    with_input_for event, :title, :text
    assert_select 'textarea.text#event_title'

    # Test my custom DatePairInput
    html = with_input_for event, :starts_at, :date_pair
    assert html.include? '2012-02-15'
    assert html.include? '11:30pm'
  end
end

If you know a better way...

Carlos Antonio da Silva

未读,
2012年4月30日 08:52:162012/4/30
收件人 plataformate...@googlegroups.com
How about creating a form with simple form, and making use of the input you're creating? Then you can just test for the output, that's basically how we do in SimpleForm :)

-- 
At.
Carlos Antonio

回复全部
回复作者
转发
0 个新帖子