more rails testing help

«

»

Hi, my name is Phil, and I suck at testing my views.

You might argue that views aren't that crucial to functionality, and that's not the job of the programmer—a designer will have to go over them anyway. If you're on a team with a designer, it might not be your job to make sure everything is displayed properly. However, there is something pretty functionally crucial about the views—forms. No amount of CSS and designer-fu will be able to fix a form that doesn't ask the right questions.

  def post_form_check(action,  params = nil,  session = nil,  flash = nil)
    get_action,  action = action if action.is_a?(Array) 
    get (get_action || action),  params.dup,  session,  flash
    assert_response : success

    assert_form_elements_present(params)

    post action,  params,  session,  flash
  end

  def assert_form_elements_present(params,  parents=[])
    params.each do |id,  value|
      next if id.to_sym == : id
      if value.is_a? Hash
        assert_form_elements_present(value,  parents + [id])
      else
        assert_select "input##{(parents + [id]).join('_')}"
      end
    end
  end

Generally when you have a page that people post data to, users get a form from an action in the same controller—often even the same action. So why not have Rails check that the form has the right inputs anyway? You've already got a list of input parameters lined up in a hash there just asking to be used.

post_form_check : new, { :name => 'Mead', :description => 'A fermented beverage made of honey, water, and yeast, often served mulled or with fruit', :alcoholic => true }

The above line will act as a post, on the :new action of your controller, but will first get the same action and ensure that there are <input> tags named name, description, and alcoholic. If you need to get a different action than you are posting to, you can use an array rather than a symbol for the action:

post_form_check [:list, :drink], { :to_drink => 32 }

It still needs a bit of work to be able to support nested hashes, but it should be helpful as it is.

Update: Now works with nested hashes.

R.I.P lilo.

« older | 2006-09-17T22:48:22Z | newer »