Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 21-30 of 34 total

Rake Task for BDD Docs

From http://www.reevoo.com/blogs/bengriffiths/2005/06/24/a-test-by-any-other-name/:

We find that the pattern ‘test_should_***_on_***’ a useful way of naming tests – it’s an idea stolen from JBehave . If this test were to fail, I’m reminded that I should (!) ask myself the question ‘should the class I’m testing do this?’ before I go on a bug-hunt. The other advantage is that I can use my test classes to generate some simple documentation for my classes. Here’s a rake target that can do just that:


   1  
   2  desc "Generate agiledox-like documentation for tests"
   3  task :agiledox do
   4    tests = FileList['test/**/*_test.rb']
   5    tests.each do |file|
   6      m = %r".*/([^/].*)_test.rb".match(file)
   7      puts m[1]+" should:\n"
   8      test_definitions = File::readlines(file).select {|line| line =~ /.*def test.*/}
   9      test_definitions.each do |definition|
  10        m = %r"test_(should_)?(.*)".match(definition)
  11        puts " - "+m[2].gsub(/_/," ")
  12      end
  13    puts "\n"
  14   end
  15  end

An example from our codebase, typing rake agiledox generates:

security_controller should:
- redirect to page stored in session on successful login
- store user object in session on successful login
- redirect to page stored in session after signup
- store user object in session after signup
- reject signup when passwords do not match
- reject signup when login too short
- report both errors if passwords dont match and username too short
- not store user in session if password not correct on signup
- remain on login page if password not correct on signup
- remove user from session on log out

rake remigrate

From http://errtheblog.com/post/3
Drops your database, recreates it, runs all migrations, then loads fixtures. Heroic.

   1  
   2  desc "Drop then recreate the dev database, migrate up, and load fixtures" 
   3  task :remigrate => :environment do
   4    return unless %w[development test staging].include? RAILS_ENV
   5    ActiveRecord::Base.connection.tables.each { |t| ActiveRecord::Base.connection.drop_table t }
   6    Rake::Task[:migrate].invoke
   7    Rake::Task["db:fixtures:load"].invoke
   8  end

Turn Rake task list into hash with Ruby

   1  
   2  Hash[*(`rake -T`.split(/\n/).collect { |l| l.match(/rake (\S+)\s+\#\s(.+)/).to_a }.collect { |l| [l[1], l[2]] }).flatten] 

Rake Freezes Rails

Stolen from: ZenSpider: http://blog.zenspider.com/archives/2006/08/upgrade_rails_n.html

If you prefer to freeze your rails checkout. I recommend stealing this rule:
   1  
   2  namespace :rails do
   3    namespace :freeze do
   4      desc "Lock to a specific rails version. Defaults to 1.1.5 or specify with RELEASE=x.y.z"
   5      task :version do
   6        rel = ENV['RELEASE'] || '1.1.5'
   7        tag = 'rel_' + rel.split(/[.-]/).join('-')
   8        rails_svn = "http://dev.rubyonrails.org/svn/rails/tags/#{tag}"
   9  
  10        puts "Freezing to #{tag} using #{rails_svn}"
  11        sh "type svn"
  12        
  13        dir = 'vendor/rails'
  14        rm_rf dir
  15        mkdir_p dir
  16        for framework in %w( railties actionpack activerecord actionmailer activesupport actionwebservice )
  17          checkout = "#{dir}/#{framework}"
  18          sh "svn export #{rails_svn}/#{framework} #{checkout}"
  19          unless test ?d, checkout then
  20            puts "ERROR: checkout missing: #{checkout}"
  21            exit 1
  22          end
  23        end
  24      end
  25    end
  26  end

and running:
   1  
   2  rake rails:freeze:version

It'll default to 1.1.5 or you can specify the tagged version you want using RELEASE=x.y.z.

Rake's missing_method found!

From http://newbieonrails.topfunky.com/articles/2006/07/28/foscon-and-living-dangerously-with-rake:
Updated from : http://mentalized.net/journal/2006/07/28/run_specific_tests_via_rake/

If you define a rule with an empty string, you can catch any task that hasn’t been defined elsewhere. This makes it easy to dynamically create rake tasks. Essentially, this is method_missing for rake!
   1  
   2  rule "" do |t|
   3    t.name 
   4    # ... do something with the name of the task  
   5  end

I experimented by writing a rule that will take a task with the format of controllername_testname and automatically run a single test from the relevant functional or unit test.
   1  
   2  ##
   3  # Run a single test in Rails.
   4  #
   5  #   rake blogs_list
   6  #   => Runs test_list for BlogsController (functional test)
   7  #
   8  #   rake blog_create
   9  #   => Runs test_create for BlogTest (unit test)
  10  
  11  rule "" do |t|
  12    if /(.*)_([^.]+)$/.match(t.name)
  13      file_name = $1
  14      test_name = $2
  15      if File.exist?("test/unit/#{file_name}_test.rb")
  16        file_name = "unit/#{file_name}_test.rb" 
  17      elsif File.exist?("test/functional/#{file_name}_controller_test.rb")
  18        file_name = "functional/#{file_name}_controller_test.rb" 
  19      else
  20        raise "No file found for #{file_name}" 
  21      end
  22      sh "ruby -Ilib:test test/#{file_name} -n /^test_#{test_name}/" 
  23    end
  24  end


Update from : http://mentalized.net/journal/2006/07/28/run_specific_tests_via_rake/
This modified version uses a different syntax (rake test:foo:bar instead rake foo_bar) and regex matching for test names.

Usage
   1  
   2  $ rake test:blog
   3  => Runs the full BlogTest unit test
   4  
   5  $ rake test:blog:create
   6  => Runs the tests matching /create/ in the BlogTest unit test
   7  
   8  $ rake test:blog_controller
   9  => Runs all tests in the BlogControllerTest functional test
  10  
  11  $ rake test:blog_controller:create
  12  => Runs the tests matching /create/ in the BlogControllerTest functional test	


Code
   1  
   2  # Run specific tests or test files
   3  # 
   4  # rake test:blog
   5  # => Runs the full BlogTest unit test
   6  # 
   7  # rake test:blog:create
   8  # => Runs the tests matching /create/ in the BlogTest unit test
   9  # 
  10  # rake test:blog_controller
  11  # => Runs all tests in the BlogControllerTest functional test
  12  # 
  13  # rake test:blog_controller
  14  # => Runs the tests matching /create/ in the BlogControllerTest functional test	
  15  rule "" do |t|
  16    # test:file:method
  17    if /test:(.*)(:([^.]+))?$/.match(t.name)
  18      arguments = t.name.split(":")[1..-1]
  19      file_name = arguments.first
  20      test_name = arguments[1..-1] 
  21      
  22      if File.exist?("test/unit/#{file_name}_test.rb")
  23        run_file_name = "unit/#{file_name}_test.rb" 
  24      elsif File.exist?("test/functional/#{file_name}_test.rb")
  25        run_file_name = "functional/#{file_name}_test.rb" 
  26      end
  27      
  28      sh "ruby -Ilib:test test/#{run_file_name} -n /#{test_name}/" 
  29    end
  30  end

Do whatever you want with the above code, it’s yours now.

Rake task to run a single rails unit or functional test

// stolen from here: http://nubyonrails.com/articles/2006/07/28/foscon-and-living-dangerously-with-rake

   1  
   2  ##
   3  # Run a single test in Rails.
   4  #
   5  #   rake blogs_list
   6  #   => Runs test_list for BlogsController (functional test)
   7  #
   8  #   rake blog_create
   9  #   => Runs test_create for BlogTest (unit test)
  10  
  11  rule "" do |t|
  12    if /(.*)_([^.]+)$/.match(t.name)
  13      file_name = $1
  14      test_name = $2
  15      if File.exist?("test/unit/#{file_name}_test.rb")
  16        file_name = "unit/#{file_name}_test.rb" 
  17      elsif File.exist?("test/functional/#{file_name}_controller_test.rb")
  18        file_name = "functional/#{file_name}_controller_test.rb" 
  19      else
  20        raise "No file found for #{file_name}" 
  21      end
  22      sh "ruby -Ilib:test test/#{file_name} -n /^test_#{test_name}/" 
  23    end
  24  end

use rake migrations to create schema in production database

// use your migrations to recreate the tables in the testing or production databases

rake migrate RAILS_ENV=production

Redefine a Rake Task

Some code to help in completely redefining a Rake task

   1  
   2  module Rake
   3    module TaskManager
   4      def redefine_task(task_class, args, &block)
   5        task_name, deps = resolve_args(args)
   6        task_name = task_class.scope_name(@scope, task_name)
   7        deps = [deps] unless deps.respond_to?(:to_ary)
   8        deps = deps.collect {|d| d.to_s }
   9        task = @tasks[task_name.to_s] = task_class.new(task_name, self)
  10        task.application = self
  11        task.add_comment(@last_comment)
  12        @last_comment = nil
  13        task.enhance(deps, &block)
  14        task
  15      end
  16    end
  17    class Task
  18      class << self
  19        def redefine_task(args, &block)
  20          Rake.application.redefine_task(self, args, &block)
  21        end
  22      end
  23    end
  24  end
  25  
  26  def redefine_task(args, &block)
  27    Rake::Task.redefine_task(args, &block)
  28  end

Rails - Build Test Environment DB from Migrations

This custom rake task builds the test environment database from the migrations rather than the schema dump of the development database. This is especially handy if you have application data inserted via your migrations that you don't want to duplicate in fixtures.

You should be able to stick this in a file called "<whatever>.rake" and put it in your "tasks" directory.

To use as a plugin, create a directory in "vendor/plugins" and call it whatever you want. Inside, create a directory called "tasks". Place this code in a file there and call it whatever you want.

   1  
   2  module Rake
   3    module TaskManager
   4      def redefine_task(task_class, args, &block)
   5        task_name, deps = resolve_args(args)
   6        task_name = task_class.scope_name(@scope, task_name)
   7        deps = [deps] unless deps.respond_to?(:to_ary)
   8        deps = deps.collect {|d| d.to_s }
   9        task = @tasks[task_name.to_s] = task_class.new(task_name, self)
  10        task.application = self
  11        task.add_comment(@last_comment)
  12        @last_comment = nil
  13        task.enhance(deps, &block)
  14        task
  15      end
  16    end
  17    class Task
  18      class << self
  19        def redefine_task(args, &block)
  20          Rake.application.redefine_task(self, args, &block)
  21        end
  22      end
  23    end
  24  end
  25  
  26  def redefine_task(args, &block)
  27    Rake::Task.redefine_task(args, &block)
  28  end
  29  
  30  namespace :db do
  31    namespace :test do
  32  
  33      desc 'Prepare the test database and migrate schema'
  34      redefine_task :prepare => :environment do
  35        Rake::Task['db:test:migrate_schema'].invoke
  36      end
  37  
  38      desc 'Use the migrations to create the test database'
  39      task :migrate_schema => 'db:test:purge' do
  40        ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
  41        ActiveRecord::Migrator.migrate("db/migrate/")
  42      end
  43    
  44    end
  45  end

Remove prereqs in Rake (Rails 1.1 and Rake 0.7)

This code will remove the prequisitive to prepare the test database in Rails. Put it in your Rakefile.

   1  
   2  module Rake
   3   class Task
   4     def remove_prerequisite(task_name)
   5       name = task_name.to_s
   6       @prerequisites.delete(name)
   7     end
   8   end
   9  end
  10  
  11  Rake::Task['test:units'].remove_prerequisite('db:test:prepare')
  12  Rake::Task['test:functionals'].remove_prerequisite('db:test:prepare')
« Newer Snippets
Older Snippets »
Showing 21-30 of 34 total