XPlayer

A blog on my daily efforts to be a better developer, and keep improving every day.

Assert_select_rjs Reloaded!

| Comments

If you ever dared to unit-test a Rails RJS action, for example something like this:
def my_ajax_action
   ...
   render(:update) do |page|
     page.replace_html 'shoppinglist', :partial => 'cart'
     page.replace_html 'items', :partial => 'layouts/items', :locals => { :cart => @cart }
   end
end
you may already know and use the assert_select_rjs testing helper, which basically will verify the structure of your RJS response.
This testing method may really help you shortening the TDD feedback loop in an AJAX-based Rails webapp, and then you’ll may even be confident enough and save one or two brittle Selenium tests.
The only problem with assert_select_rjs is that is (IMHO) poorly documented and rarely googled about.
So, this is my turn to give back what we discovered.
If you have a Rails webapp using jQuery as javascript framework, you may have a hard time using assert_select_rjs correctly, and this is why:
for jQuery, this is the correct way to use assert_select_rjs:
assert_select_rjs :replace_html, '#shoppinglist'
it’s important the ‘#’ prefix here to refer to DOM element IDs, since the notation without ‘#’ will work only if your app uses Prototype.
Another nice thing to know is the way to make assertion on the selection matched by the assert_select_rjs.
For example, this code
assert_select_rjs :replace_html, '#shoppinglist' do
    assert_select '#shipping_cost_description', /Shipping costs for France/
    assert_select '#shipping_cost_value', /€ 12,30/
end
will verify that the section replaced inside the ‘shoppinglist’ element will match the two followings assetions.