Browse the Ruby on Rails Community.

You are here: Browse Railsplugins Form Test Helper

Form Test Helper

  • Requires EdgeRails or the assert_select plugin.

This plugin uses assert_select to verify and manipulate your forms. It solves the problem we’ve all run into where you change the form but the test doesn’t break because you’re doing this in the test: post :create, :book => {:name => ‘Pickaxe’, :category => 1, :out_of_print => 0} assert_response :success

Instead, work with the form directly! submit_form do |form| # or select by dom_id or url if multiple forms on the page form.book.name = ‘Pickaxe’ form.book.category.options => [[‘Programming’, ‘1’], [‘Self-help’, ‘2’], ...] form.book.category = “Programming” # Can set using the option label or the option value form.book.out_of_print.uncheck # Uncheck the checkbox end assert_response :success

...or simply: submit_form :book => {:name => ‘Pickaxe’, :category => ‘Programming’, :out_of_print => false}

What’s the benefit of this over post :create…? It uses the action of the form, it verifies that the form and the fields you specify are present and not misspelled, and it preserves any hidden or default values that may be in the form.

Features: * Can also select_form / submit_form by DOM id or form action. Without arguments, expects only one form. select_form messages_path # selecting by action (URL) select_form ‘message_form’ # selects <form id=”message_form”> book.category = “Programming” >> book.classic.check # Definitely one of the greats >> end => “1” >> book = {:rating => ‘12’} # You can make a hash of field values… => {:rating=>‘12’} >> form.book.update(book) # and then assign it to the book object of the form => {“rating”=>#<formtesthelper::field>> form.book.rating # Did it work? (It did) => “12” >> form.action => ”/books/create” >> form.request_method => :post
  1. TODO: Show form.submit and how all the params from the form are submitted (once the bug with recycle! is fixed (Ruby on Rails Ticket #6353)) >> follow_redirect! => 200 >> select_link(‘Edit’).follow # Can verify the presence of and follow links => 200

Dan Kubb’s test example:

new_book = { :name => ‘Pickaxe’, :category => ‘Programming’, :classic => true, }

get :new

submit_form do |form| form.book.update(new_book) end

book = assigns(:book)

assert_kind_of Book, book assert_valid book

new_book.each do |attribute,expects| assert_equal expects, book.send(attribute) end

Acknowledgments

form_test_helper was inspired by the excellent work of choonkeat on hpricot_forms, which is based on the hpricot library. If you prefer hpricot over assert_select, give hpricot_forms a try!

NOTE: This description has been extracted from the Plugin README and so the formatting may need updating to make browser friendly