Created
May 2, 2010 22:16
-
-
Save jorgemanrubia/387503 to your computer and use it in GitHub Desktop.
Code examples from my post 'Testing PURE javascript templates from RSpec'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="person-template" class="name"/> | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Code from the post Testing PURE javascript templates from RSpec