Skip to content

Instantly share code, notes, and snippets.

@pcreux pcreux/mktest
Created Jun 14, 2017

Embed
What would you like to do?
Generate a test file. `mktest app/models/user.rb` => `test/models/user_test.rb`
#!/usr/bin/env ruby
DESC = "
Generate test file
Example: mktest app/services/user/create.rb will generate test/services/user/create_test.rb
"
FILES = ARGV
if FILES.empty?
puts DESC
exit 1
end
require 'fileutils'
FILES.each do |file_path|
unless File.exists?(file_path)
puts "#{file_path} does not exists - Skipping..."
next
end
_, top_dir, *sub_dirs, file = file_path.split('/')
test_dir_path = ["test", top_dir, sub_dirs].flatten.join('/')
test_file_path = [test_dir_path, file.gsub(/\.rb$/, "_test.rb")].join('/')
namespaces = sub_dirs.map { |str| str.split('_').map(&:capitalize).join }
klass_name = file.gsub(/\.rb$/, '').split('_').map(&:capitalize).join
full_klass_name = (namespaces + [klass_name]).join('::')
depth = sub_dirs.size + 1
code = %|require_relative '#{"../" * depth }test_helper'
class #{full_klass_name}Test < ActiveSupport::TestCase
end
|
if File.exists?(test_file_path)
puts "#{test_file_path} exists - Skipping..."
else
puts "#{test_file_path} created!"
FileUtils.mkpath test_dir_path
File.open(test_file_path, 'w') do |f|
f.puts code
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.