Skip to content

Instantly share code, notes, and snippets.

@jtrim
Created April 23, 2014 14:12
Show Gist options
  • Save jtrim/11216715 to your computer and use it in GitHub Desktop.
Save jtrim/11216715 to your computer and use it in GitHub Desktop.
Runs specs based on a fuzzy match of the file path
#!/usr/bin/env ruby
require 'rubygems'
require 'thor'
require 'pry'
class SmartSpec < Thor
option :all, type: :boolean, aliases: ['-a']
desc 'fuzzy [PATTERN] *OR* smartspec -- [PATTERN]', 'Find specs matching PATTERN and run one or all of them.'
long_desc <<-DESC
This is the default action of smartspec, so:\x5
`smartspec fuzzy 'app mod user'`\x5
...and:\x5
`smartspec -- 'app mod user'`\x5
are synonymous.
By default, if the supplied pattern matches more than one spec, only one is chosen, and this choice is based on:\x5
1. the length of the filename, so 'user_spec.rb' would be chosen over 'super_user_spec.rb' when both are in the same directory, and:\x5
2. the length of the path to the file, so 'spec/models/user_spec.rb' would be chosen over 'spec/models/admin/user_spec.rb'\x5
OPTIONS
-a, --all: Instead of choosing a spec based on the matching rules above, run all specs that match PATTERN
EXAMPLES
Run `spec/models/user_spec.rb`:\x5
`smartspec -- 'mod user'
Run both `spec/models/user_spec.rb` and `spec/models/admin/user_spec.rb`:\x5
`smartspec -a -- 'mod user'
Run any spec that relates to users:\x5
`smartspec -a -- user`
DESC
def fuzzy(*patterns)
files = patterns.flat_map do |pattern|
pattern_matches = spec_files.grep Regexp.new(pattern.gsub(" ", ".*/"))
if options[:all]
pattern_matches
else
pattern_matches.sort do |a,b|
if File.basename(a).length == File.basename(b).length
File.dirname(a).length <=> File.dirname(b).length
else
File.basename(a).length <=> File.basename(b).length
end
end.first
end
end
cmd = "bundle exec rspec #{files.join(" ")}"
puts cmd
system cmd
end
default_task :fuzzy
private
def spec_files
@spec_files ||= Dir["spec/**/*"].to_a
end
end
SmartSpec.start(ARGV)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment