Skip to content

Instantly share code, notes, and snippets.

@mrsimo
Created June 16, 2017 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrsimo/4917d2f02074b0b3a6e4d419a6bc107f to your computer and use it in GitHub Desktop.
Save mrsimo/4917d2f02074b0b3a6e4d419a6bc107f to your computer and use it in GitHub Desktop.
Rewrite tests from def test_ to test "" and setup/teardown blocks
require 'parser/current'
require 'byebug'
class FixDefTest < Parser::Rewriter
def on_def(node)
name, args_node, body_node = *node
if name.to_s.start_with?("test_")
replace(node.location.keyword, "test")
replace(node.location.name, %("#{name.to_s.gsub(/^test_/, "").gsub("_", " ")}" do))
end
if name == :setup
replace(node.location.keyword, "setup")
replace(node.location.name, "do")
end
if name == :teardown
replace(node.location.keyword, "teardown")
replace(node.location.name, "do")
end
end
end
ARGV.each do |file|
if File.exists?(file)
code = File.read(file)
buffer = Parser::Source::Buffer.new('(example)')
buffer.source = code
parser = Parser::CurrentRuby.new
ast = parser.parse(buffer)
rewriter = FixDefTest.new
# Rewrite the AST, returns a String with the new form.
File.open(file, "w") { |f| f.write(rewriter.rewrite(buffer, ast)) }
else
puts "Skipping `#{file}`, not a file"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment