require "#{File.expand_path(File.dirname(__FILE__))}/helper"

describe "Tilt" do
  with_environment :development
  
  delegate :render, :to => Crystal::Template
  
  before :all do
    @dir = "#{File.expand_path(File.dirname(__FILE__))}/tilt_spec"
    ::RenderResult = OpenObject.new
    
    class TemplateContextStub < Crystal::TemplateContext
      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
    
    $LOAD_PATH << @dir
  end
  
  after :all do
    $LOAD_PATH.delete @dir
    remove_constants %w(RenderResult)
  end
  
  # def render template_name, options = {}
  #   options[:context_class] ||= TemplateContextStub
  #   Crystal::Template.render template_name, options
  # end
  # 
  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.?$/
    RenderResult.erb_capture.should =~ /^text for capturing.?$/
    
    render('/concat_and_capture.haml').should =~ /^text for concatenation.?$/
    RenderResult.haml_capture.should =~ /^text for capturing.?$/
  end
  
  it "yield" do
    render('/yield.erb'){|variable| "content for :#{variable}"}.should == "Layout, content for :content"
  end  
  
  describe "mixed template types" do
    it "broken haml concat (from error)" do
      render(
        '/mixed_templates/broken_haml_concat_haml',
        :context_class => TemplateContextStub
      ).gsub("\n", "").should == "<div>some content</div>"
      
      render(
        '/mixed_templates/broken_haml_concat_erb',
        :context_class => TemplateContextStub
      ).gsub("\n", "").should == "<div>some content</div>"
    end
  
    it "broken erb concat (from error)" do
      render(
        '/mixed_templates/broken_erb_concat_erb', 
        :context_class => TemplateContextStub
      ).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_class => TestTC).gsub("\n", '').should == 
      "<form_tag><form_field>some field</form_field></form_tag>"
  end
end