1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Forms in Mechanize


Manipulating and submitting forms is about as easy as you could imagine in Mechanize. As expected, the form objects (such as check boxes, buttons and text fields) have methods like "click" that mirror real-browser input.

Before you can manipulate a form, you have to first find a form from the Mechanize::Page object..

Referring To Fields

Once you've found a form, you'll have a Mechanize::Form object. To refer to any of the fields, you typically use the method_missing method, with the name attribute of the form field. If a page contains the following HTML:

<form action="/subscribe" method="POST">
  <input type="text" name="username" />
  <input type="text" name="email" />
  <input type="password" name="password" />

And the form variable contains a Mechanize::Form object referring to this form, you could access the value of each of these fields using form.username, form.email and form.password. Filling in these fields is just as you'd expect as well, simply assign to these "attributes." You could set the username like form.username = 'user'.

However, the method_missing way of accessing fields is not perfect. If you wanted to access a form with the name of value or even class, both of which are already defined methods, using the method_missing idiom would fail in perhaps devious ways. For that reason, it's perhaps safer to use the Mechanize::Form#[] and Mechanize::Form#[]= methods. Meaning you could refer to the username field like form['username'] and fill it in like form['username'] = 'user'.

In addition to referring to fields by name, you can also iterate over or search for fields you may not know the exact name of. To do this, use one of the following methods.

  • fields - Returns a list of all field names.
  • buttons - Returns a list of all button fields.
  • file_uploads - Returns a list of all file selection fields, where a user may upload a file.
  • radiobuttons - Returns a list of all radio buttons. Note that this is a group of all radio buttons, not necessarily in any order or grouped correctly.
  • checkboxes - A list of all check boxes.
  • submits - Returns a subset of buttons, returning only buttons that will submit the form.
  • resets - Similar to submits, returns the reset buttons.
  • texts - Returns all text fields, but not text-like fields such as textarea or password fields.
  • textarea - All textareas.

Alternatively, there is yet another way to find form fields. This way should be familiar, and should allow you to access any form elements regardless of access methods. This way is, of course, the familiar _with idiom. Specifically, the field_with and fields_with methods. For a detailed explanation of the _with idiom, see the discussion on finding links.

  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. The Mechanize 2.0 Handbook
  6. Forms

©2014 About.com. All rights reserved.