# encoding: utf-8
require 'spec_helper'

describe "Tilt" do
  with_view_path "#{spec_dir}/views"
  
  inject template: :template
  
  def render *a, &b
    template.render *a, &b
  end
  
  before :all do
    class TemplateContextStub < Rad::Template::Context
      def tag name, content = nil, &block      
        if block_given?
          content = capture(&block)
          concat "<#{name}>#{content}</#{name}>"
        else
          content = content
          "<#{name}>#{content}</#{name}>"
        end      
      end
    end
  end
  
  before do
    $render_result = OpenObject.new
    rad.mode = :development, true
  end
  after{rad.mode = :test, true}
  
  it "haml should be ugly" do
    render('/ugly.haml').should_not =~ /^\s/
  end
  
  it "should correctly show error lines" do
    lambda{render('/errors.erb')}.should raise_error(/line with error/){|e| e.backtrace.first.should =~ /^.+errors\.erb:2.+$/}
    lambda{render('/errors.haml')}.should raise_error(/line with error/){|e| e.backtrace.first.should =~ /^.+errors\.haml:2.+$/}
  end
  
  it "concat & capture" do    
    render('/concat_and_capture.erb').should =~ /^text for concatenation.?$/
    $render_result.erb_capture.should =~ /^text for capturing.?$/
    
    render('/concat_and_capture.haml').should =~ /^text for concatenation.?$/
    $render_result.haml_capture.should =~ /^text for capturing.?$/
  end
  
  it "yield" do
    render('/yield.erb'){|variable| "content for :#{variable}"}.should == "Layout, content for :content"
  end  
  
  it "should render non-ASCII symbols (from error)" do
    render('/encoding/erb').should =~ /»/
    render('/encoding/haml').should =~ /»/    
  end
  
  describe "mixed template types" do
    it "broken haml concat (from error)" do
      render(
        '/mixed_templates/broken_haml_concat_haml',
        context: TemplateContextStub.new
      ).gsub("\n", "").should == "<div>some content</div>"
      
      render(
        '/mixed_templates/broken_haml_concat_erb',
        context: TemplateContextStub.new
      ).gsub("\n", "").should == "<div>some content</div>"
    end
  
    it "broken erb concat (from error)" do
      render(
        '/mixed_templates/broken_erb_concat_erb', 
        context: TemplateContextStub.new
      ).gsub("\n", "").should == "haml content<div>\tsome content</div>"
    end
  end
  
  
  it "nested capture & concat (from error)" do
    class TestTC < TemplateContextStub
      def form_tag &block
        html = capture &block
        concat(tag(:form_tag, html))
      end
      
      def form_field &block
        html = capture &block
        concat(tag(:form_field, html))
      end
    end
    
    render('/nested_capture_and_concat', context: TestTC.new).gsub("\n", '').should == 
      "<form_tag><form_field>some field</form_field></form_tag>"
  end
end