RSpec2 and Autotest 19 Mar 2011

Autotest automatically runs your tests in background after a file in the project is saved, which lets you concentrate on the job at hand rather than manually running the tests every time you make a change.This approach helps in really speeding the development process, saving a lot of time.
There are multiple ways to show the output apart from the terminal, one of which is the notification area in Ubuntu as shown in the image below. Other than visual people use different sound notifications too.

Notification Popup

alt pass alt fail

Setup

Use RVM for managing different versions of Ruby on a system. Read this post on how to install it and get started.

 
#Use Ruby 1.9.2
rvm use 1.9.2
 
#Generate a new rails 3 application
rails new todo_list -T -J -d mysql

Install Rspec, Cucumber & Webrat Gemfile

group :test do
  gem 'webrat'
  gem 'cucumber'
  gem 'cucumber-rails'
  gem 'rspec'
  gem 'rspec-rails'
end

Paste in config/application.rb to load Rspec generator

config.generators do |g|
  g.test_framework :rspec, :fixture => true
end

Install Rspec in the application

rails g rspec:install

Generate a scaffold

bundle install
 
rails g scaffold User email:string first_name:string last_name:string password_salt:string password_hash:string
 
rake db:create && rake db:migrate

AutoTest

AutoTest Getting Started Guide

Install ZenTest Gem

gem install ZenTest

Install Notification library for Ubuntu

sudo apt-get install libnotify-bin

Test libnotify

notify-send "Hello"

Now goto your home directory and create a .autotest file and paste the following code

Edit ~/.autotest

Autotest.add_hook :initialize do |autotest|
  autotest.add_mapping(/^spec\/.*_spec\.rb$/) do |file|
    file
  end
 
  autotest.add_mapping(/^spec\/(controllers|helpers|lib|models|views)\/.*_spec\.rb$/) do|file|
    file
  end
 
end

module Autotest::Notify
  def self.notify(title, msg, img, pri='low', time=3000)
    `notify-send -i #{img} -u #{pri} -t #{time} '#{title}' '#{msg}'`
  end
 
  Autotest.add_hook :ran_command do |autotest|
    begin
      results = autotest.results
      output = results.last.gsub(/\e\[(\d+)m/,'')
      images = "~/Pictures/autotest_images"
      if output  =~ /[1-9]\d*\sfailures?/
        notify "Failure", "#{output}", "#{images}/fail.png", 'critical', 10000
      else
        notify "Passed", "#{output}", "#{images}/pass.png",'normal', 10000
      end
    rescue Exception => e
      p "#{e.message} \n #{e.backtrace}"
    end
  end
end

Run Autotest in your project root

autotest

Download Source for the above example.
It uses an authentication example for explaining Rails3, Rspec2 and Cucumber working together.

Download Autotest file

Thoughts

comments powered by Disqus