functional test skeleton

namespace :test do
  namespace :functionals do
    
    desc "Generate functional testing skeleton"
    task :generate => :environment do
      dir = ENV['dir']
      if dir.blank?
        puts "Warning! \nNothing is done, please identify the controllers directory! \ne.g. rake test:functionals:generate dir=contents/courses"
      else
        Gen.new.build(File.expand_path('app/controllers/'+dir, RAILS_ROOT)) 
      end
    end
    
  end
end

class Gen
  def build(dir)
    Dir[dir + '/*'].each{|f|
      File.directory?(f) ? build(f) : parse_controller_file(f)
    }
  end
  
  def parse_controller_file(file)
    @clauses = ["all_fixtures"]
    @actions = [{:action => "setup", :text => "    login_as users(:admin)"}]
    action_name, params, response = nil, nil, "success"
    
    File.open(file).each{|line|
      break if line =~ /private/
      # A new action begins, store the info of privious action
      if line =~ /def\s/
        create_action(action_name, params, response)
        action_name, params, response = $'.chop.strip , [], "success"
      else
        #get needed params and response
        if line =~/params\[:\w*\]/
          para = $&.gsub(/params\[|\]/,"")
          params << (para) unless params.nil? or params.include?(para)
        end
        response = "redirect" if line =~ /redirect_to/
      end
    }
    create_action(action_name, params, response)
    
    write_test_file(file)
  end
  
  def write_test_file(file) 
    test_file_name = file.gsub(/app\/controllers/,"#{$`}test/functional#{$'}").gsub(".rb","_test.rb")
    return unless File.exist?(test_file_name)
    
    to_write = []
    test_file = File.open(test_file_name)
    ignore = false
    test_file.each{|line|
      if line =~ /def\s/
        action_name = $'.chop.strip
        ignore = action_name =~ /test_truth/  #delete test_truth
        #don't append actions that have exist
        if @actions.map{|t| t[:action]}.include?(action_name)
          @actions = @actions.select{|t| t[:action]!=action_name}
        end
      end
      line = line.chop
      @clauses.delete(line.strip)
      to_write << line unless ignore
    }
    
    @clauses = @clauses.map{|t| "  "+t}
    @actions.each{|t|
      @clauses << %{  def #{t[:action]}\n#{t[:text]}\n  end}
    }
    to_write.insert(to_write.size-1, @clauses.join("\n\n")) unless @clauses.join("\n\n").blank?
    to_write[to_write.size-1] = "end"
    
    test_file.close
    File.open(test_file_name, 'w') do |f|  
      f.puts to_write.join("\n")  
    end  
  end
  
  def create_action(action_name, params, response)
    unless action_name.nil?
      method = ["create", "update", "destroy"].include?(action_name) ? "post" : "get"
      text = %{    #{method} :#{action_name}#{', '+ params.map{|t| t+" =>''"}.join(", ") unless params.blank?}\n    assert_response :#{response}}
      @actions << {:action=> "test_"+action_name, :text=>text} 
    end
  end
  
end
 

你可能感兴趣的:(F#,Rails)