Agile Web Development

Build it. Launch it. Love it.

Hpricot Forms

An attempt to create similar functionality to HtmlUnit to do web-based navigation tests.


In a hypothetical application login application, we write the functional test like this:

  def test_login_logout
    page = get :new            # first, let's get to the login page
    form = page.forms.first    # next, get a reference to the form

    # form.field_names => ["user[login]", "user[password]"]
                              # form.field_names returns you the input fields
                              # available in the form

    form["options[]"]        = ["secure", "remember"]
                                                          # e.g. options[] fields are checkboxes

    form["user[login]"]    = "Joe"
    form["user[password]"] = "topsecret"
                                                          # these are single-value inputs

    page = form.submit(self)   # after setting the form values, submit it
                              # 'page' now references the page after login

    assert_response :success

    # page.links               # returns you an array of links found on the page

    page = page.links("@id='signout'")
                              # locate the sign-out link by its html ID
                              # attribute and click it

    assert_response :success

Notice we didn’t need to handle things like session and where the form submits to explicitly. It simply goes to where its supposed to - as rendered. And yes, as you do submit() and click() you might actually cross different controllers. HpricotForms handles that for you.

The main thing I like about this API is, the field names in the form are real. When you modify your action template (.rhtml files) but forgot to change your test and controllers - traditionally, your tests will still pass because you were passing in parameters explicitly, e.g.

  post :login, {:user => {:login => "Joe", :password => "topsecret"}}

even though your HTML form fields might have been changed to "account[login]" and "account[passwd]".

But HpricotForms will raise an exception when you try to set values into fields that does not exist in the rendered form.


License Rails' (MIT)
Rating (2 votes)
Owner Chew Choon Keat
Created 24 July 2006


Add a comment