Rails 3.1 and the assert_select_jquery

October 8, 2011


This post was originally published in the Rambling Labs Blog on October 8, 2011.


Diving a little into rails 3.1, I’m really liking some of the stuff I’ve found, like the easy Ajax integration for the views and the functional tests to ensure that the behavior of the controllers is the expected one.

There is one particular method, assert_select_jquery, that I just don’t understand why it works how it works.

Let’s say you have an Ajax request whose view to return is content.js.erb like this:

if($('#container').is(':not(:visible)')) $('#container').show('blind', 1000);
$('#container').html('<%= render @content %>');

Ok, the page renders as expected, but, as you can see, this code is not too great. We’ll talk about that later. So, say you also have a test, in the corresponding controller test file, that looks like this:

test 'the container html is replaced when rendered' do
  assert_select_jquery :html, '#container'
end

You run the tests with rake test:functionals and… Awesome! The test passes. Now, you improve the JavaScript a little and you write this

var container = $('#container');
if(container.is(':not(:visible)')) container.show('blind', 1000);
container.html('<%= render @content %>')

Once again, the page renders as expected. But the test fails!!! :(

Why? I don’t really know. It seems like the assert_select_jquery :html, '#container' can only match $('#container').html("whatever") and not container.html('whatever'). Notice that they only match the double quotes inside the html method and not the single quotes. That’s even worse.

Are they enforcing bad JavaScript code? Bad jQuery practices? I’m sure there has to be a better way to test it out, but I’m yet to find it out.