Rambling Labs Blog Ramblings on software development

  • Rails 3.1 and the assert_select_jquery

    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'

    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.

  • blog comments powered by Disqus