When talking about upgrading memory to Rails 3.0, I mentioned that I’d had trouble testing a bit of the unobtrusive JavaScript code. Specifically, I had a file answer.js.erb that contained the following:

$('answer').update("<%= escape_javascript(render :partial =>
'answer', :object => @item) %>");

and I wanted to take apart the HTML returned by that render :partial section.

I eventually came up with a solution that I’m happy with, so I’ll mention it here in case anybody else runs into the same problem and ends up here via Googling.

The partial in question contained a p element with class qa; let’s assume that it’s body is supposed to be text_to_assert_on. Then here’s the test that I ended up with:

  def unescape_javascript(escaped)
    escaped.gsub("\\'", "'").gsub("\\\"", "\"").gsub("\\n", "\n").
      gsub("\\\\", "\\").gsub("<\\/", "</")
  end

  def assert_encoded_update(body, element_to_update)
    assert_not_nil(/\$\('(.*)'\)\.update\("(.*)"\);/ =~ body)
    assert_equal(element_to_update, $1)
    yield(HTML::Document.new(unescape_javascript($2)).root)
  end

  def test_get_answer
    get :index
    post :answer, :format => 'js', :item => @one.id

    assert_encoded_update(response.body, "answer") do |replacement|
      assert_select(replacement, "p.qa", "text_to_assert_on")
    end
  end

I don’t claim that this is perfect (there are probably more cases that unescape_javascript should handle), but it worked well for my purpose.

Post Revisions:

This post has not been revised since publication.