Skip to content

Instantly share code, notes, and snippets.

@dreamr
Created August 24, 2010 00:47
Show Gist options
  • Save dreamr/546668 to your computer and use it in GitHub Desktop.
Save dreamr/546668 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'active_support'
APPD = "#{File.dirname(__FILE__)}/.."
MODD = "#{File.dirname(__FILE__)}/../spec/models"
FACTD = "#{File.dirname(__FILE__)}/../spec/factories"
class SpecGenerator
ASSOCIATION_CONVERSION_TABLE = [
["has_many", "have_many"],
["has_one", "have_one"],
["belongs_to", "belong_to"]
]
def run
model_sources.each { |file| generate_specs_for_model(file) }
end
private
def model_sources
Dir["#{APPD}/app/models/*.rb"]
end
def generate_specs_for_model(file)
spec_file_name = "#{MODD}/#{File.basename(file, '.rb')}_spec.rb"
puts "#{spec_file_name} already exists (skipping)" and return if File.exists?(spec_file_name)
File.open(spec_file_name, "w+") do |f|
klass = File.basename(file, '.rb').classify
f.puts "require File.expand_path(File.dirname(__FILE__) + ‘/../spec_helper’)"
f.puts "describe #{klass} do"
validations_for_conversion(file).each { |v| f.puts "\t#{v}\n" }
f.puts "end"
end
end
def validations_for_conversion(file)
validations = []
File.open(file, "r") do |f|
while (line = f.gets)
validations << get_association_values(line) if line_has_association?(line)
end
end
validations
end
def line_has_association?(line)
found = false
ASSOCIATION_CONVERSION_TABLE.each { |key| found = true if line.match(key[0]) }
found
end
def get_association_values(line)
association_code = ""
ASSOCIATION_CONVERSION_TABLE.each do |key|
matches = line.scan(/(#{key[0]}) (\:\w+)/).flatten
association_code = "it { should #{key[1]}( #{matches[1]} ) }" if matches.size > 0
end
association_code
end
end
sg = SpecGenerator.new
sg.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment