I am BARRY HESS > Blog

Assert_select Selectors Using Regular Expressions

Occasionally in Rails I will run into something that I know should be available even though I can’t remember running into it in the past. The beauty of the Rails OSS community is that most times the thing I want has already been implemented. Recently I ran into a situation where my bible, or should I say bible_s_, did not uncover the Rails magic for me.* The last step, as always, is to look in the API.

In testing, I like to verify that JavaScript UI bits are all wired up properly. In this case I wanted check what was in an anchor tag’s onclick parameter in a generalized way. A perfect situation for a regular expression, but heck if I knew how to sick the regular expression on an onclick parameter. Enter the examples section on assert_select in the API. Witness assert_select substitution values:

# Use substitution values
assert_select "ol>li#?", /item-\d+/

# All input fields in the form have a name
assert_select "form input" do
  assert_select "[name=?]", /.+/  # Not empty


This allows me to check my JavaScript wiring:

def test_report_filter_button_should_be_wired_to_toggle_filter_div
  get :index
  assert_select "#filter_button a[onclick*=?]", /report_filter.+toggle/

Basically, this selector looks in the element with the id of “filter_button”. From there it looks for a link whose onclick parameter includes “report_filter” and “toggle”. So something like the following would match:

<div id='filter_button'>
  <a href="#" onclick="$('report_filter').toggle();false;">

Pretty convenient.

* I only checked my Rails books in a reference-manual-like manner. In my cursory search I did not see any reference to substitution values for assert_select.