Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

Write functional tests in Rails using CSS selectors

By Peter Cooper / July 9, 2006

Assert Select

assert_select is a plugin by Assaf Arkin that allows you to use CSS selectors in your functional tests to check that certain HTML elements match your assertions. On the surface, this isn't too far removed from using why's Hpricot to do assertions on HTML, but in reality having the full power of CSS selectors available changes everything (Update! Hpricot has XPath and CSS addressing too!). Some examples:

# Form includes four input fields
assert_select "form input", 4

# Page does not have any forms in it.
assert_select "form", false, "Page must contain no forms"

def test_login_form_has_all_fields
    get :login
    assert_select "form[action=http://myapp/login] input" do |inputs|
        assert_equal 3, inputs.size
        assert_select inputs[0], "input[type=name][name=username]"
        assert_select inputs[1], "input[type=password][name=password]"
        assert_select inputs[2], "input[type=submit][value=Login]"

More examples here.


  1. Pingback: InfoHatter Blog!

Other Posts to Enjoy

Twitter Mentions