I am surprised to find little about testing RJS in rails, with the exception of ARTS. However, assert_select_rjs seems to be the replacement to ARTS. This is nice, as we have now one less plugin to worry about. (I am of the opinion that testing plugins should be integrated into core if it is used in more than one test)
I’ll show you one example.
Let’s say that we have scaffolded our controllers, and now have a RJS function that we want to call when we destroy a membership. We first create our test
old_count = Membership.count
delete :destroy, :id => 1
assert_equal old_count-1, Membership.count
assert_select_rjs :replace_html, “membership-action”
I am just testing if replace_html was called on the ‘membership-action’ element, without regard to what content is replaced into. If you want to test the content being replaced, pass the value to be compared as the second parameter of assert_select_rjs. E.g.
[source:ruby] assert_select_rjs :replace_html, “membership-action”, “Some Content”[/source]
Test and watch it go red.
Now we create our RJS template to make the test go green. The content can be anything, since I did not test for equality of the content to be replaced.
[source:ruby]page.replace_html ‘membership-action’, :partial => ‘memberships/join_link’[/source]
Run the test and feel the green.
Looking under the hood of
assert_select_rjs, it seems that it is taking a copy of
@response.body, and then running a Regular Expression match with the test values. Something worth knowing.
It also checks for
“No RJS statement that replaces or inserts HTML content”
Just remember to put format.js in your controller, and you should be alright.