Tuesday, March 6, 2012

Automate the process of running the test (watchr gem used with rails and rspec)

I today tried watchr gem while writing my unit test in rails application.It automate the process of running unit test. Watchr automatically run the test for the files which are change. That means if I changed Employee model then it will automaticall run employee_spec.rb . I found this gem very useful as save lot of time for manually run the test.

Installation watchr
Step 1.) Installing the gem
          gem install watchr
If you are using it with rails better bundle install the gem after adding the following code in gemfile

group :development, :test do
  gem 'rspec-rails'
  gem 'watchr'
end


Step 2.) Create .watchr file in root directory and add the following code:

def run_spec(file)
  unless File.exist?(file)
    puts "#{file} does not exist"
    return
  end
  puts "Running #{file}"
  system "bundle exec rspec #{file}"
  puts
end

watch("spec/.*/*_spec.rb") do |match|
  run_spec match[0]
end

watch("app/(.*/.*).rb") do |match|
  run_spec %{spec/#{match[1]}_spec.rb}
end


Step 3.) run the following command:
watchr .watchr


Now you can make change in your code and then automatically respective spec will run.

References :
https://github.com/mynyml/watchr
http://www.rubyinside.com/how-to-rails-3-and-rspec-2-4336.html