O'Reilly logo

Test Driven Ajax (on Rails) by Phlip

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Simulate Ajax Server Hits with xhr :get

If we double-click on that DIV, Ajax.Updater calls /wiki/-edit_node, and that doesn't work yet. So now test-first its behavior. It should return a FORM to edit this DIV:

  def test_wiki_yaml_action
    yaml_to_xhtml(get_omap)

    xhr :get,
        :edit_node,
        :page_name => 'WikiTestPage',
        :ypath => 'node:test_uncle_wiggily:script'

    assert_xml @response.body

    assert_xpath '/form' do
      assert_xpath 'textarea[ @name = "node_contents" ]' do |node|
        assert_match /tests uncle wiggily/, node.text
      end
    end
  end

GUI Bug Confession

Our DIV responds to double-clicks, even after the editor displays. So double-clicking a word to select it will refresh the DIV, and throw our edits away! The fix is edit_node, which should send more JavaScript that erases the ondblclick attribute.

The test requires our WikiController to grow its very first method:

class WikiController < ApplicationController

  def edit_node
    yar = YarWiki.new(params[:page_name])
    y = YAML.parse_file(yar.yaml_path)
    x = Builder::XmlMarkup.new
    params[:ypath] =~ /^node(:.*)/
    ypath = $1.gsub(':', '//')

    x.form do
      x.textarea :name   => 'node_contents',
                 :cols   => 60,
                 :rows   => 3 do
        x.text! y.select(ypath)[0].value
      end
    end

    render :text => x.target!
  end
end

Ajax Action Guards

All actions that serve Ajax should start with:

  return unless (request.xhr? or RAILS_ENV != 'production')

This prevents everyone from calling that action except Ajax events and tests. (I have omitted them in the interest of space.)

That code had to reconstitute an HTML ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required