RJS Assertions

For example, previously I was testing that when I entered the postcode for Buckingham Palace, the address would be filled for me:




12345678910
def test_when_selecting_address_address_fields_populated  xhr :post, :fill_address, :selected_address => 1  assert_response :success  assert_equal "text/javascript",     @response.headers["Content-Type"]  assert /Buckingham Palace/.match(    @response.body  )end

Unfortunately, this relies on regular expression matching, there’s no guarantee that the address that’s recovered actually replaces the text in the address first line text box. Any number of templating problems could cause it not to be rendered correctly, and I’d end up with a broken app that wouldn’t necessarily have tests failing.

At the time I wondered about whether it would be possible to write code for the RJS emitted script as I did with the rest of Rails’ functional tests—using `assert_tag` etc.

Well thanks to RJS assertions I can now. The previous test now looks as follows:

def test_when_selecting_address_address_fields_populated  xhr :post, :fill_address, :selected_address => 1end

assert_response :successassert_equal "text/javascript; charset=UTF-8",  @response.headers["Content-Type"]assert_rjs_tag :tag => "input",  :rjs => {:block => 'originAddressEntry' },  :tag => "input",  :attributes => {    :id => "from_address_line_1",    :value => "Buckingham Palace"     }

Much better, it’s far more communicative and the intent is clear. It’s also much more natural when writing test first now—“I want some RJS script that’s going to update this block and I’m looking for a tag that looks as follows…”

In the above test I’m asserting that I’m replacing the `originAddressEntry` division with the emitted RJS script, and that I’m looking for an `input` tag, with the id of `from_address_line_1` that will have it’s value set to Buckingham Palace.

I really encourage anyone doing any RJS work to use the additional assertions, and check out Brasten’s blog post on the plugin. There’s no reason not to test your RJS controller code thoroughly now!