Skip to content

Instantly share code, notes, and snippets.

@therealadam
Created February 22, 2012 15:40
Show Gist options
  • Save therealadam/1885599 to your computer and use it in GitHub Desktop.
Save therealadam/1885599 to your computer and use it in GitHub Desktop.
Run focused unit tests in Vim, with a little help from Ruby.
  • Move focus to somewhere on your PATH
  • Drop focus.vim in ~/.vim/plugins
  • Put focus on a key. I went with nnoremap <leader>tf :call Focus().
  • Open a test/unit file, put your cursor inside a test method and run focus.
  • Profit
#!/usr/bin/env ruby
class Focus
def initialize(filename)
@filename = filename
end
def test_command(line_no)
"ruby -Ilib:test #{@filename} --name #{test_for(line_no)}"
end
# Totally borrowed from Drew Olson
# https://github.com/drewolson/ruby_focused_unit_test_vim/blob/master/plugin/ruby_focused_unit_test.vim
def test_for(line_no)
method_name = ''
line_no.downto(1) do |l|
line = contents[l]
if line =~ /def (test_\w+)/
method_name = $1
break
elsif line =~ /test "([^"]+)"/ || line =~ /test '([^']+)'/
method_name = "test_" + $1.split(" ").join("_")
break
end
end
method_name
end
def contents
@contents ||= File.read(@filename).split("\n")
end
end
if __FILE__ == $0
puts "focus <file> <line>" && exit(1) unless ARGV.length == 2
file = ARGV[0]
line = Integer(ARGV[1])
focus = Focus.new(file)
exec focus.test_command(line)
end
" TODO
" - put this in my vim config
" - decide how to bundle focus script
" - reap the benefits
function! Focus()
let l = line('.')
let f = expand('%')
echom "You are on line " . l . " of file " . f
exec "!ruby focus.rb " . f . " " . l
endfunction
require 'rubygems'
require 'active_support'
require 'test/unit'
require 'focus'
class FocusTest < ActiveSupport::TestCase
def test_finds_the_name_for_a_normal_method
test_name = "test_finds_the_name_for_a_normal_method"
assert_equal test_name, focus.test_for(__LINE__)
assert_equal "ruby -Ilib:test #{the_file} --name #{test_name}", focus.test_command(__LINE__)
end
test "finds the line for a sugared method" do
test_name = "test_finds_the_line_for_a_sugared_method"
assert_equal test_name, focus.test_for(__LINE__)
assert_equal "ruby -Ilib:test #{the_file} --name #{test_name}", focus.test_command(__LINE__)
end
def focus
Focus.new(the_file)
end
def the_file
__FILE__
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment