Testing RJS Templates
I’ve been using RJS Templates very heavily in my recent projects. Of course, if you’ve used them, you know how helpful they can be. But as a unit/functional test addict, I’ve been frustrated by my inability to write really good test cases for my AJAX actions. I’m sure the Rails guys will work something into future versions of Rails, but in the mean time, I’ve thrown together a small collection of assertions that give you pretty good test coverage of AJAX/RJS responses. (Link Below)
Installation
You can install the plugin from your Rails application directory by running:
script/plugin install -x svn://rubyforge.org/var/svn/rjsassertions/trunk
Example
The following example was pulled straight from my current project.
Say you have an action that triggers the following RJS template:
1 2 3 4 5 6 7 8 9 10 11 |
page.replace_html 'details_column_left', :partial => 'field', :collection => @left_column, :locals => {:values => @field_hash} page.replace_html 'details_column_right', :partial => 'field', :collection => @right_column, :locals => {:values => @field_hash} page.hide 'information_save_button' page.show 'information_edit_button' page.hide 'field_errors' |
The action JavaScript response sent to the browser might end up looking something like:
1 2 3 4 5 6 |
Element.update("details_column_left",
"<label for=\"field[35]\">Preferred:</label>");
Element.update("details_column_right",
"<label for=\"field[34]\">Locations:</label>");
Element.hide("information_save_button");
Element.show("information_edit_button"); |
Using RJS Assertions, you can now assert various conditions on this response. Note the example assertions below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def test_updating_fields post :update_fields, {:id => @joe_schmoe.id, :field => {'1' => 'New Value'}}, logged_in_session assert_rjs_tag :rjs => {:block => 'details_column_left' }, :tag => 'label', :content => 'Preferred:' assert_rjs_tag :rjs => {:block => 'details_column_right' }, :tag => 'label', :content => 'Locations:' assert_rjs_no_tag :rjs => {:block => 'details_column_left' }, :content => 'Left Value One!!!' assert_rjs_visual_effect 'information_save_button', :hide assert_rjs_visual_effect 'information_edit_button', :show end |
It was fairly quickly thrown together for the purpose of a project, so the Ruby code could use a little TLC. Also, I’ll be adding assertions for the various RJS methods in time. If you wish to help out, please visit the RubyForge project page.
Relevant Links
Leave a Reply