Skip to content

Instantly share code, notes, and snippets.

@jorgemanrubia
Created May 2, 2010 22:16
Show Gist options
  • Save jorgemanrubia/387503 to your computer and use it in GitHub Desktop.
Save jorgemanrubia/387503 to your computer and use it in GitHub Desktop.
Code examples from my post 'Testing PURE javascript templates from RSpec'
<div id="person-template" class="name"/>
require 'spec_helper'
describe "persons/_person_template.html.erb" do
it "should render a proper container for the person" do
person = {:name=>"Jorge"}
render_javascript_template(person) do |rendered_text|
rendered_text.should have_selector("div.name", :content=>"Jorge")
end
end
end
module ViewHelpers
def render_javascript_template(data)
render
include_javascript_files
yield do_render_javascript_template(data)
end
def include_javascript_files
%w{jquery.js pure.js}.each {|file| js("load('public/javascripts/#{file}');")}
end
def as_javascript_string(text)
text.split("\n").collect{|line| "'#{line}'"}.join('+')
end
def template_id_from_path(template_path)
template_path.gsub(/^(.+\/_)/, "").gsub(/_/, "-").gsub(/.html.erb$/, "")
end
def do_render_javascript_template(data)
json_data = as_javascript_string(data.to_json)
template_id = template_id_from_path(self.class.description_parts.first)
js("var data=$.parseJSON(#{json_data});")
js("var $template = $('##{template_id}').clone().appendTo($('<div></div>'));")
js("var renderedElement = $template.autoRender(data);")
return js("$('<div></div>').append(renderedElement).html()")
end
end
@jorgemanrubia
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment