Permalink
Browse files

Replace test cases with Rspec.

Also some changes towards Rails 4 compatibility.
  • Loading branch information...
1 parent 5516818 commit 9d062ed98e35243ac58d185cb2cb934e303c9c43 @rroblak committed Sep 2, 2013
View
@@ -19,3 +19,4 @@ rdoc
pkg
## PROJECT::SPECIFIC
+Gemfile.lock
View
2 .rspec
@@ -0,0 +1,2 @@
+--color
+--format progress
View
13 Gemfile
@@ -0,0 +1,13 @@
+source 'https://rubygems.org'
+
+gem 'activesupport'
+gem 'activerecord'
+
+group :development do
+ gem 'jeweler'
+end
+
+group :test do
+ gem 'rspec'
+ gem 'sqlite3'
+end
View
@@ -16,30 +16,6 @@ rescue LoadError
puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
end
-require 'rake/testtask'
-Rake::TestTask.new(:test) do |test|
- test.libs << 'lib' << 'test'
- test.pattern = 'test/*_test.rb'
- test.verbose = true
-end
-
-begin
- require 'rcov/rcovtask'
- Rcov::RcovTask.new do |test|
- test.libs << 'test'
- test.pattern = 'test/**/test_*.rb'
- test.verbose = true
- end
-rescue LoadError
- task :rcov do
- abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
- end
-end
-
-task :test => :check_dependencies
-
-task :default => :test
-
require 'rdoc/task'
Rake::RDocTask.new do |rdoc|
version = File.exist?('VERSION') ? File.read('VERSION') : ""
@@ -49,3 +25,7 @@ Rake::RDocTask.new do |rdoc|
rdoc.rdoc_files.include('README*')
rdoc.rdoc_files.include('lib/**/*.rb')
end
+
+require 'rspec/core/rake_task'
+RSpec::Core::RakeTask.new(:spec)
+task :default => :spec
View
@@ -46,29 +46,44 @@ def attr_accessible(*opts)
end
end
+ def log(msg)
+ puts msg if @opts['debug']
+ end
+
def load_models
- puts "Searching in #{@opts['model_dir']} for models" if @opts['debug']
- Dir[Dir.pwd + '/' + @opts['model_dir']].sort.each do |f|
- puts "Processing file #{f}" if @opts['debug']
- # parse file name and path leading up to file name and assume the path is a module
- f =~ /models\/(.*).rb/
- # split path by /, camelize the constituents, and then reform as a formal class name
- parts = $1.split("/").map {|x| x.camelize}
+ log("Searching in #{@opts['model_dir']} for models")
+
+ Dir[File.join(Dir.pwd, @opts['model_dir'])].sort.each do |f|
+ log("Processing file #{f}")
+
+ dirname, basename = File.split(f)
+
+ dir_array = dirname.split(File::SEPARATOR)
+
+ # Find index of last occurence of 'models' in path
+ models_index = nil
+ dir_array.each_with_index {|x, i| models_index = i if x == 'models'}
+
+ model_dir_array = dir_array[models_index + 1..-1]
# Initialize nested model namespaces
- parts.clip.inject(Object) do |x, y|
- if x.const_defined?(y)
- x.const_get(y)
+ model_dir_array.inject(Object) do |parent, child|
+ child = child.camelize
+
+ if parent.const_defined?(child)
+ parent.const_get(child)
else
- x.const_set(y, Module.new)
+ parent.const_set(child, Module.new)
end
end
- model = parts.join("::")
require f
- puts "Detected model #{model}" if @opts['debug']
- @models.push model if @opts['models'].include?(model) || @opts['models'].empty?
+ model = File.join(model_dir_array + [File.basename(basename, '.rb')]).camelize
+
+ log("Detected model #{model}")
+
+ @models << model if @opts['models'].include?(model) || @opts['models'].empty?
end
end
@@ -103,17 +118,18 @@ def dump_model(model)
create_hash = ""
options = ''
rows = []
- arr = []
- arr = model.find(:all, @ar_options) unless @opts['no-data']
+ arr = nil
+ unless @opts['no-data']
+ arr = model.all
+ arr.limit(@ar_options[:limit]) if @ar_options[:limit]
+ end
arr = arr.empty? ? [model.new] : arr
arr.each_with_index { |r,i|
attr_s = [];
r.attributes.each do |k,v|
- if (@opts['rails4'] || (model.attr_accessible[:default].include? k) || @opts['without_protection'] || @opts['with_id'])
- pushed_key = dump_attribute(attr_s,r,k,v)
- @last_record.push k if pushed_key
- end
+ pushed_key = dump_attribute(attr_s,r,k,v)
+ @last_record.push k if pushed_key
end
rows.push "#{@indent}{ " << attr_s.join(', ') << " }"
}
File renamed without changes.
@@ -1,4 +1,3 @@
class ChildSample < AbstractSample
- attr_accessible :name
end
@@ -1,3 +1,2 @@
class Nested::Sample < ActiveRecord::Base
- attr_accessible :name
end
View
@@ -0,0 +1,2 @@
+class Sample < ActiveRecord::Base
+end
@@ -0,0 +1,119 @@
+require 'spec_helper'
+
+describe SeedDump::Perform do
+ before(:all) do
+ ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:')
+
+ ActiveRecord::Schema.define(:version => 1) do
+ create_table 'child_samples', :force => true do |t|
+ t.string 'name'
+ t.datetime 'created_at', :null => false
+ t.datetime 'updated_at', :null => false
+ end
+
+ create_table 'samples', :force => true do |t|
+ t.string 'string'
+ t.text 'text'
+ t.integer 'integer'
+ t.float 'float'
+ t.decimal 'decimal'
+ t.datetime 'datetime'
+ t.datetime 'timestamp'
+ t.time 'time'
+ t.date 'date'
+ t.binary 'binary'
+ t.boolean 'boolean'
+ t.datetime 'created_at', :null => false
+ t.datetime 'updated_at', :null => false
+ end
+ end
+ end
+
+ before do
+ @sd = SeedDump::Perform.new
+
+ @env = {'MODEL_DIR' => 'spec/models/*.rb',
+ 'FILE' => Dir.pwd + '/spec/db/seeds.rb',
+ 'VERBOSE' => false,
+ 'DEBUG' => false,
+ 'RAILS4' => ENV['RAILS4']}
+ end
+
+ it 'should load models from the specified directory' do
+ @sd.setup(@env)
+
+ @sd.load_models
+
+ @sd.models.should eq(["AbstractSample", "ChildSample", "Sample"])
+ end
+
+ it 'should support nested models' do
+ @env['MODEL_DIR'] = 'spec/models/**/*.rb'
+
+ @sd.setup @env
+
+ @sd.load_models
+
+ @sd.models.should eq(['AbstractSample', 'ChildSample', 'Nested::Sample', 'Sample'])
+ end
+
+ it 'should not include timestamps if the TIMESTAMPS parameter is false' do
+ @env['TIMESTAMPS'] = false
+
+ @sd.setup @env
+
+ @sd.load_models
+
+ @sd.dump_models
+
+ @sd.last_record.should_not include('created_at')
+ end
+
+ it 'should include timestamps if the TIMESTAMPS parameter is true' do
+ @env['TIMESTAMPS'] = true
+
+ @sd.setup @env
+
+ @sd.load_models
+
+ @sd.dump_models
+
+ @sd.last_record.should include('created_at')
+ end
+
+ it 'should include ids if the WITH_ID parameter is true' do
+ @env['WITH_ID'] = true
+
+ @sd.setup @env
+
+ @sd.load_models
+
+ @sd.dump_models
+
+ @sd.last_record.should include('id')
+ end
+
+ it 'should skip abstract models' do
+ @env['MODELS'] = 'AbstractSample'
+
+ @sd.setup @env
+
+ @sd.load_models
+
+ @sd.dump_models
+
+ @sd.last_record.should eq([])
+ end
+
+ it 'should use the create method specified in the CREATE_METHOD parameter' do
+ @env['CREATE_METHOD'] = 'create!'
+
+ @sd.setup @env
+
+ @sd.load_models
+
+ @sd.dump_models
+
+ @sd.instance_variable_get(:@seed_rb).should include('create!')
+ end
+end
View
@@ -0,0 +1,15 @@
+require 'seed_dump/perform'
+require 'active_support/core_ext/string'
+require 'active_record'
+
+RSpec.configure do |config|
+ config.treat_symbols_as_metadata_keys_with_true_values = true
+ config.run_all_when_everything_filtered = true
+ config.filter_run :focus
+
+ # Run specs in random order to surface order dependencies. If you find an
+ # order dependency and want to debug it, you can fix the order by providing
+ # the seed, which is printed after each run.
+ # --seed 1234
+ config.order = 'random'
+end
View
@@ -1,54 +0,0 @@
-# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
-
-bharathiyar:
- string: Poetry of Subramaniya Bharathiyar
- text: யாமறிந்த மொழிகளிலே தமிழ்மொழி போல் இனிதாவது எங்கும் காணோம்,
-பாமரராய் விலங்குகளாய், உலகனைத்தும் இகழ்ச்சிசொலப் பான்மை கெட்டு,
-நாமமது தமிழரெனக் கொண்டு இங்கு வாழ்ந்திடுதல் நன்றோ? சொல்லீர்!
-தேமதுரத் தமிழோசை உலகமெலாம் பரவும்வகை செய்தல் வேண்டும்.
- integer: 1
- float: 3.3333
- decimal: 9.99
- datetime: 1902-07-21 17:01:31
- timestamp: 1900-07-21 17:01:31
- time: 1903-07-21 17:01:31
- date: 1904-07-21
- binary:
- boolean: false
-
-pushkin:
- string: Pushkin's Bronze Horseman
- text: На берегу пустынных волн
-Стоял он, дум великих полн,
-И вдаль глядел. Пред ним широко
-Река неслася; бедный чёлн
-По ней стремился одиноко.
-По мшистым, топким берегам
-Чернели избы здесь и там,
-Приют убогого чухонца;
-И лес, неведомый лучам
-В тумане спрятанного солнца,
-Кругом шумел.
- integer: 1
- float: 1.5
- decimal: 9.99
- datetime: 2012-07-21 17:01:31
- timestamp: 2012-07-21 17:01:31
- time: 2012-07-21 17:01:31
- date: 2012-07-21
- binary:
- boolean: false
-poem:
- string: Anglo-Saxon Rune Poem
- text: ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ
-ᛋᚳᛖᚪᛚ᛫ᚦᛖᚪᚻ᛫ᛗᚪᚾᚾᚪ᛫ᚷᛖᚻᚹᛦᛚᚳ᛫ᛗᛁᚳᛚᚢᚾ᛫ᚻᛦᛏ᛫ᛞᚫᛚᚪᚾ
-ᚷᛁᚠ᛫ᚻᛖ᛫ᚹᛁᛚᛖ᛫ᚠᚩᚱ᛫ᛞᚱᛁᚻᛏᚾᛖ᛫ᛞᚩᛗᛖᛋ᛫ᚻᛚᛇᛏᚪᚾ
- integer: 1
- float: 1.9
- decimal: 4.55
- datetime: 2012-07-21 17:01:31
- timestamp: 2012-07-21 17:01:31
- time: 2012-07-21 17:01:31
- date: 2012-07-21
- binary:
- boolean: false
View
@@ -1,3 +0,0 @@
-class Sample < ActiveRecord::Base
- attr_accessible :binary, :boolean, :date, :datetime, :decimal, :float, :integer, :string, :text, :time, :timestamp
-end
Oops, something went wrong.

0 comments on commit 9d062ed

Please sign in to comment.