Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

add josé valim's rspec-rails generators

  • Loading branch information...
commit f06aa507280f8f9e6316c9bd5f72e640269a49b1 1 parent c487e51
David Chelimsky dchelimsky authored
Showing with 1,001 additions and 4 deletions.
  1. +3 −0  example_app_template.rb
  2. +25 −0 lib/generators/rspec-rails.rb
  3. +26 −0 lib/generators/rspec-rails/controller/controller_generator.rb
  4. +23 −0 lib/generators/rspec-rails/controller/templates/controller_spec.rb
  5. +12 −0 lib/generators/rspec-rails/controller/templates/view_spec.rb
  6. +11 −0 lib/generators/rspec-rails/helper/helper_generator.rb
  7. +11 −0 lib/generators/rspec-rails/helper/templates/helper_spec.rb
  8. +28 −0 lib/generators/rspec-rails/install/install_generator.rb
  9. +182 −0 lib/generators/rspec-rails/install/templates/lib/tasks/rspec.rake
  10. +6 −0 lib/generators/rspec-rails/install/templates/script/autospec.tt
  11. +10 −0 lib/generators/rspec-rails/install/templates/script/spec.tt
  12. +9 −0 lib/generators/rspec-rails/install/templates/script/spec_server.tt
  13. +2 −0  lib/generators/rspec-rails/install/templates/spec/rcov.opts
  14. +4 −0 lib/generators/rspec-rails/install/templates/spec/spec.opts
  15. +51 −0 lib/generators/rspec-rails/install/templates/spec/spec_helper.rb
  16. +12 −0 lib/generators/rspec-rails/integration/integration_generator.rb
  17. +4 −0 lib/generators/rspec-rails/integration/templates/integration_spec.rb
  18. +21 −0 lib/generators/rspec-rails/mailer/mailer_generator.rb
  19. +3 −0  lib/generators/rspec-rails/mailer/templates/fixture
  20. +14 −0 lib/generators/rspec-rails/mailer/templates/mailer_spec.rb
  21. +22 −0 lib/generators/rspec-rails/model/model_generator.rb
  22. +19 −0 lib/generators/rspec-rails/model/templates/fixtures.yml
  23. +13 −0 lib/generators/rspec-rails/model/templates/model_spec.rb
  24. +12 −0 lib/generators/rspec-rails/observer/observer_generator.rb
  25. +5 −0 lib/generators/rspec-rails/observer/templates/observer_spec.rb
  26. +11 −0 lib/generators/rspec-rails/plugin/plugin_generator.rb
  27. +5 −0 lib/generators/rspec-rails/plugin/templates/%file_name%_spec.rb.tt
  28. +5 −0 lib/generators/rspec-rails/plugin/templates/test_helper.rb
  29. +112 −0 lib/generators/rspec-rails/scaffold/scaffold_generator.rb
  30. +127 −0 lib/generators/rspec-rails/scaffold/templates/controller_spec.rb
  31. +25 −0 lib/generators/rspec-rails/scaffold/templates/edit_spec.rb
  32. +27 −0 lib/generators/rspec-rails/scaffold/templates/index_spec.rb
  33. +25 −0 lib/generators/rspec-rails/scaffold/templates/new_spec.rb
  34. +67 −0 lib/generators/rspec-rails/scaffold/templates/routing_spec.rb
  35. +22 −0 lib/generators/rspec-rails/scaffold/templates/show_spec.rb
  36. +34 −2 lib/rspec/rails/example/controller_example_group.rb
  37. +13 −2 lib/rspec/rails/example/request_example_group.rb
3  example_app_template.rb
View
@@ -1 +1,4 @@
run "gem bundle"
+
+
+
25 lib/generators/rspec-rails.rb
View
@@ -0,0 +1,25 @@
+require 'generators/named_base'
+
+module Rspec
+ module Generators
+ class Base < Rails::Generators::NamedBase #:nodoc:
+ def self.source_root
+ @_rspec_source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'rspec', generator_name, 'templates'))
+ end
+ end
+ end
+end
+
+module Rails
+ module Generators
+ class GeneratedAttribute #:nodoc:
+ def input_type
+ @input_type ||= if type == :text
+ "textarea"
+ else
+ "input"
+ end
+ end
+ end
+ end
+end
26 lib/generators/rspec-rails/controller/controller_generator.rb
View
@@ -0,0 +1,26 @@
+require 'generators/rspec'
+
+module Rspec
+ module Generators
+ class ControllerGenerator < Base
+ argument :actions, :type => :array, :default => [], :banner => "action action"
+
+ class_option :template_engine, :desc => "Template engine to generate view files"
+
+ def create_controller_files
+ template 'controller_spec.rb',
+ File.join('spec/controllers', class_path, "#{file_name}_controller_spec.rb")
+ end
+
+ def create_view_files
+ empty_directory File.join("spec", "views", file_path)
+
+ actions.each do |action|
+ @action = action
+ template 'view_spec.rb',
+ File.join("spec", "views", file_path, "#{@action}.html.#{options[:template_engine]}_spec.rb")
+ end
+ end
+ end
+ end
+end
23 lib/generators/rspec-rails/controller/templates/controller_spec.rb
View
@@ -0,0 +1,23 @@
+require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper')
+
+describe <%= class_name %>Controller do
+
+<% if actions.empty? -%>
+ #Delete this example and add some real ones
+<% else -%>
+ #Delete these examples and add some real ones
+<% end -%>
+ it "should use <%= class_name %>Controller" do
+ controller.should be_an_instance_of(<%= class_name %>Controller)
+ end
+
+<% for action in actions -%>
+
+ describe "GET '<%= action %>'" do
+ it "should be successful" do
+ get '<%= action %>'
+ response.should be_success
+ end
+ end
+<% end -%>
+end
12 lib/generators/rspec-rails/controller/templates/view_spec.rb
View
@@ -0,0 +1,12 @@
+require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../../spec_helper')
+
+describe "/<%= file_name %>/<%= @action %>.html.<%= options[:template_engine] %>" do
+ before(:each) do
+ render '<%= file_name %>/<%= @action %>'
+ end
+
+ #Delete this example and add some real ones or delete this file
+ it "should tell you where to find the file" do
+ response.should have_tag('p', %r[Find me in app/views/<%= file_path %>/<%= @action %>])
+ end
+end
11 lib/generators/rspec-rails/helper/helper_generator.rb
View
@@ -0,0 +1,11 @@
+require 'generators/rspec'
+
+module Rspec
+ module Generators
+ class HelperGenerator < Base
+ def create_helper_files
+ template 'helper_spec.rb', File.join('spec/helpers', class_path, "#{file_name}_helper_spec.rb")
+ end
+ end
+ end
+end
11 lib/generators/rspec-rails/helper/templates/helper_spec.rb
View
@@ -0,0 +1,11 @@
+require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper')
+
+describe <%= class_name %>Helper do
+
+ #Delete this example and add some real ones or delete this file
+ it "is included in the helper object" do
+ included_modules = (class << helper; self; end).send :included_modules
+ included_modules.should include(<%= class_name %>Helper)
+ end
+
+end
28 lib/generators/rspec-rails/install/install_generator.rb
View
@@ -0,0 +1,28 @@
+module Rspec
+ module Generators
+ class InstallGenerator < Rails::Generators::Base
+ add_shebang_option!
+
+ desc <<DESC
+Description:
+ Copy rspec files to your application.
+DESC
+
+ def self.source_root
+ @source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
+ end
+
+ def copy_lib_files
+ directory 'lib'
+ end
+
+ def copy_script_files
+ directory 'script'
+ end
+
+ def copy_spec_files
+ directory 'spec'
+ end
+ end
+ end
+end
182 lib/generators/rspec-rails/install/templates/lib/tasks/rspec.rake
View
@@ -0,0 +1,182 @@
+gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9
+rspec_gem_dir = nil
+Dir["#{RAILS_ROOT}/vendor/gems/*"].each do |subdir|
+ rspec_gem_dir = subdir if subdir.gsub("#{RAILS_ROOT}/vendor/gems/","") =~ /^(\w+-)?rspec-(\d+)/ && File.exist?("#{subdir}/lib/spec/rake/spectask.rb")
+end
+rspec_plugin_dir = File.expand_path(File.dirname(__FILE__) + '/../../vendor/plugins/rspec')
+
+if rspec_gem_dir && (test ?d, rspec_plugin_dir)
+ raise "\n#{'*'*50}\nYou have rspec installed in both vendor/gems and vendor/plugins\nPlease pick one and dispose of the other.\n#{'*'*50}\n\n"
+end
+
+if rspec_gem_dir
+ $LOAD_PATH.unshift("#{rspec_gem_dir}/lib")
+elsif File.exist?(rspec_plugin_dir)
+ $LOAD_PATH.unshift("#{rspec_plugin_dir}/lib")
+end
+
+# Don't load rspec if running "rake gems:*"
+unless ARGV.any? {|a| a =~ /^gems/}
+
+begin
+ require 'spec/rake/spectask'
+rescue MissingSourceFile
+ module Spec
+ module Rake
+ class SpecTask
+ def initialize(name)
+ task name do
+ # if rspec-rails is a configured gem, this will output helpful material and exit ...
+ require File.expand_path(File.dirname(__FILE__) + "/../../config/environment")
+
+ # ... otherwise, do this:
+ raise <<-MSG
+
+#{"*" * 80}
+* You are trying to run an rspec rake task defined in
+* #{__FILE__},
+* but rspec can not be found in vendor/gems, vendor/plugins or system gems.
+#{"*" * 80}
+MSG
+ end
+ end
+ end
+ end
+ end
+end
+
+Rake.application.instance_variable_get('@tasks').delete('default')
+
+spec_prereq = File.exist?(File.join(RAILS_ROOT, 'config', 'database.yml')) ? "db:test:prepare" : :noop
+task :noop do
+end
+
+task :default => :spec
+task :stats => "spec:statsetup"
+
+desc "Run all specs in spec directory (excluding plugin specs)"
+Spec::Rake::SpecTask.new(:spec => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['spec/**/*_spec.rb']
+end
+
+namespace :spec do
+ desc "Run all specs in spec directory with RCov (excluding plugin specs)"
+ Spec::Rake::SpecTask.new(:rcov) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['spec/**/*_spec.rb']
+ t.rcov = true
+ t.rcov_opts = lambda do
+ IO.readlines("#{RAILS_ROOT}/spec/rcov.opts").map {|l| l.chomp.split " "}.flatten
+ end
+ end
+
+ desc "Print Specdoc for all specs (excluding plugin specs)"
+ Spec::Rake::SpecTask.new(:doc) do |t|
+ t.spec_opts = ["--format", "specdoc", "--dry-run"]
+ t.spec_files = FileList['spec/**/*_spec.rb']
+ end
+
+ desc "Print Specdoc for all plugin examples"
+ Spec::Rake::SpecTask.new(:plugin_doc) do |t|
+ t.spec_opts = ["--format", "specdoc", "--dry-run"]
+ t.spec_files = FileList['vendor/plugins/**/spec/**/*_spec.rb'].exclude('vendor/plugins/rspec/*')
+ end
+
+ [:models, :controllers, :views, :helpers, :lib, :integration].each do |sub|
+ desc "Run the code examples in spec/#{sub}"
+ Spec::Rake::SpecTask.new(sub => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList["spec/#{sub}/**/*_spec.rb"]
+ end
+ end
+
+ desc "Run the code examples in vendor/plugins (except RSpec's own)"
+ Spec::Rake::SpecTask.new(:plugins => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['vendor/plugins/**/spec/**/*_spec.rb'].exclude('vendor/plugins/rspec/*').exclude("vendor/plugins/rspec-rails/*")
+ end
+
+ namespace :plugins do
+ desc "Runs the examples for rspec_on_rails"
+ Spec::Rake::SpecTask.new(:rspec_on_rails) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['vendor/plugins/rspec-rails/spec/**/*_spec.rb']
+ end
+ end
+
+ # Setup specs for stats
+ task :statsetup do
+ require 'code_statistics'
+ ::STATS_DIRECTORIES << %w(Model\ specs spec/models) if File.exist?('spec/models')
+ ::STATS_DIRECTORIES << %w(View\ specs spec/views) if File.exist?('spec/views')
+ ::STATS_DIRECTORIES << %w(Controller\ specs spec/controllers) if File.exist?('spec/controllers')
+ ::STATS_DIRECTORIES << %w(Helper\ specs spec/helpers) if File.exist?('spec/helpers')
+ ::STATS_DIRECTORIES << %w(Library\ specs spec/lib) if File.exist?('spec/lib')
+ ::STATS_DIRECTORIES << %w(Routing\ specs spec/routing) if File.exist?('spec/routing')
+ ::STATS_DIRECTORIES << %w(Integration\ specs spec/integration) if File.exist?('spec/integration')
+ ::CodeStatistics::TEST_TYPES << "Model specs" if File.exist?('spec/models')
+ ::CodeStatistics::TEST_TYPES << "View specs" if File.exist?('spec/views')
+ ::CodeStatistics::TEST_TYPES << "Controller specs" if File.exist?('spec/controllers')
+ ::CodeStatistics::TEST_TYPES << "Helper specs" if File.exist?('spec/helpers')
+ ::CodeStatistics::TEST_TYPES << "Library specs" if File.exist?('spec/lib')
+ ::CodeStatistics::TEST_TYPES << "Routing specs" if File.exist?('spec/routing')
+ ::CodeStatistics::TEST_TYPES << "Integration specs" if File.exist?('spec/integration')
+ end
+
+ namespace :db do
+ namespace :fixtures do
+ desc "Load fixtures (from spec/fixtures) into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z."
+ task :load => :environment do
+ ActiveRecord::Base.establish_connection(Rails.env)
+ base_dir = File.join(Rails.root, 'spec', 'fixtures')
+ fixtures_dir = ENV['FIXTURES_DIR'] ? File.join(base_dir, ENV['FIXTURES_DIR']) : base_dir
+
+ require 'active_record/fixtures'
+ (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/).map {|f| File.join(fixtures_dir, f) } : Dir.glob(File.join(fixtures_dir, '*.{yml,csv}'))).each do |fixture_file|
+ Fixtures.create_fixtures(File.dirname(fixture_file), File.basename(fixture_file, '.*'))
+ end
+ end
+ end
+ end
+
+ namespace :server do
+ daemonized_server_pid = File.expand_path("#{RAILS_ROOT}/tmp/pids/spec_server.pid")
+
+ desc "start spec_server."
+ task :start do
+ if File.exist?(daemonized_server_pid)
+ $stderr.puts "spec_server is already running."
+ else
+ $stderr.puts %Q{Starting up spec_server ...}
+ FileUtils.mkdir_p('tmp/pids') unless test ?d, 'tmp/pids'
+ system("ruby", "script/spec_server", "--daemon", "--pid", daemonized_server_pid)
+ end
+ end
+
+ desc "stop spec_server."
+ task :stop do
+ unless File.exist?(daemonized_server_pid)
+ $stderr.puts "No server running."
+ else
+ $stderr.puts "Shutting down spec_server ..."
+ system("kill", "-s", "TERM", File.read(daemonized_server_pid).strip) &&
+ File.delete(daemonized_server_pid)
+ end
+ end
+
+ desc "restart spec_server."
+ task :restart => [:stop, :start]
+
+ desc "check if spec server is running"
+ task :status do
+ if File.exist?(daemonized_server_pid)
+ $stderr.puts %Q{spec_server is running (PID: #{File.read(daemonized_server_pid).gsub("\n","")})}
+ else
+ $stderr.puts "No server running."
+ end
+ end
+ end
+end
+
+end
6 lib/generators/rspec-rails/install/templates/script/autospec.tt
View
@@ -0,0 +1,6 @@
+<%= shebang %>
+gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9
+ENV['RSPEC'] = 'true' # allows autotest to discover rspec
+ENV['AUTOTEST'] = 'true' # allows autotest to run w/ color on linux
+system((RUBY_PLATFORM =~ /mswin|mingw/ ? 'autotest.bat' : 'autotest'), *ARGV) ||
+ $stderr.puts("Unable to find autotest. Please install ZenTest or fix your PATH")
10 lib/generators/rspec-rails/install/templates/script/spec.tt
View
@@ -0,0 +1,10 @@
+<%= shebang %>
+if ARGV.any? {|arg| %w[--drb -X --generate-options -G --help -h --version -v].include?(arg)}
+ require 'rubygems' unless ENV['NO_RUBYGEMS']
+else
+ gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9
+ ENV["RAILS_ENV"] ||= 'test'
+ require File.expand_path(File.dirname(__FILE__) + "/../config/environment") unless defined?(RAILS_ROOT)
+end
+require 'spec/autorun'
+exit ::Spec::Runner::CommandLine.run
9 lib/generators/rspec-rails/install/templates/script/spec_server.tt
View
@@ -0,0 +1,9 @@
+<%= shebang %>
+gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9
+
+puts "Loading Rails environment"
+ENV["RAILS_ENV"] ||= 'test'
+require File.expand_path(File.dirname(__FILE__) + "/../config/environment") unless defined?(RAILS_ROOT)
+
+require 'optparse'
+require 'spec/rails/spec_server'
2  lib/generators/rspec-rails/install/templates/spec/rcov.opts
View
@@ -0,0 +1,2 @@
+--exclude "spec/*,gems/*"
+--rails
4 lib/generators/rspec-rails/install/templates/spec/spec.opts
View
@@ -0,0 +1,4 @@
+--colour
+--format progress
+--loadby mtime
+--reverse
51 lib/generators/rspec-rails/install/templates/spec/spec_helper.rb
View
@@ -0,0 +1,51 @@
+# This file is copied to ~/spec when you run 'ruby script/generate rspec'
+# from the project root directory.
+ENV["RAILS_ENV"] ||= 'test'
+require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
+require 'spec/autorun'
+require 'spec/rails'
+
+# Requires supporting files with custom matchers and macros, etc,
+# in ./support/ and its subdirectories.
+Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
+
+Spec::Runner.configure do |config|
+ # If you're not using ActiveRecord you should remove these
+ # lines, delete config/database.yml and disable :active_record
+ # in your config/boot.rb
+ config.use_transactional_fixtures = true
+ config.use_instantiated_fixtures = false
+ config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
+
+ # == Fixtures
+ #
+ # You can declare fixtures for each example_group like this:
+ # describe "...." do
+ # fixtures :table_a, :table_b
+ #
+ # Alternatively, if you prefer to declare them only once, you can
+ # do so right here. Just uncomment the next line and replace the fixture
+ # names with your fixtures.
+ #
+ # config.global_fixtures = :table_a, :table_b
+ #
+ # If you declare global fixtures, be aware that they will be declared
+ # for all of your examples, even those that don't use them.
+ #
+ # You can also declare which fixtures to use (for example fixtures for test/fixtures):
+ #
+ # config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
+ #
+ # == Mock Framework
+ #
+ # RSpec uses it's own mocking framework by default. If you prefer to
+ # use mocha, flexmock or RR, uncomment the appropriate line:
+ #
+ # config.mock_with :mocha
+ # config.mock_with :flexmock
+ # config.mock_with :rr
+ #
+ # == Notes
+ #
+ # For more information take a look at Spec::Runner::Configuration and Spec::Runner
+end
12 lib/generators/rspec-rails/integration/integration_generator.rb
View
@@ -0,0 +1,12 @@
+require 'generators/rspec'
+
+module Rspec
+ module Generators
+ class IntegrationGenerator < Base
+ def create_integration_file
+ template 'integration_spec.rb',
+ File.join('spec/integration', class_path, "#{table_name}_spec.rb")
+ end
+ end
+ end
+end
4 lib/generators/rspec-rails/integration/templates/integration_spec.rb
View
@@ -0,0 +1,4 @@
+require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper')
+
+describe "<%= class_name.pluralize %>" do
+end
21 lib/generators/rspec-rails/mailer/mailer_generator.rb
View
@@ -0,0 +1,21 @@
+require 'generators/rspec'
+
+module Rspec
+ module Generators
+ class MailerGenerator < Base
+ argument :actions, :type => :array, :default => [], :banner => "method method"
+
+ def create_mailer_files
+ template "mailer_spec.rb",
+ File.join('spec', 'models', class_path, "#{file_name}_spec.rb")
+ end
+
+ def create_fixtures_files
+ actions.each do |action|
+ @action, @path = action, File.join(file_path, action)
+ template "fixture", File.join("spec/fixtures", @path)
+ end
+ end
+ end
+ end
+end
3  lib/generators/rspec-rails/mailer/templates/fixture
View
@@ -0,0 +1,3 @@
+<%= class_name %>#<%= @action %>
+
+Find me in app/views/<%= @path %>
14 lib/generators/rspec-rails/mailer/templates/mailer_spec.rb
View
@@ -0,0 +1,14 @@
+require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper')
+
+describe <%= class_name %> do
+<% for action in actions -%>
+ it "should deliver <%= action.gsub("_", " ") %> message" do
+ @expected.subject = '<%= class_name %>#<%= action %>'
+ @expected.body = read_fixture('<%= action %>')
+ @expected.date = Time.now
+
+ @expected.encoded.should == <%= class_name %>.create_<%= action %>(@expected.date).encoded
+ end
+
+<% end -%>
+end
22 lib/generators/rspec-rails/model/model_generator.rb
View
@@ -0,0 +1,22 @@
+require 'generators/rspec'
+
+module Rspec
+ module Generators
+ class ModelGenerator < Base
+ argument :attributes, :type => :array, :default => [], :banner => "field:type field:type"
+ class_option :fixture, :type => :boolean
+
+ def create_test_file
+ template 'model_spec.rb', File.join('spec/models', class_path, "#{file_name}_spec.rb")
+ end
+
+ hook_for :fixture_replacement
+
+ def create_fixture_file
+ if options[:fixture] && options[:fixture_replacement].nil?
+ template 'fixtures.yml', File.join('spec/fixtures', "#{table_name}.yml")
+ end
+ end
+ end
+ end
+end
19 lib/generators/rspec-rails/model/templates/fixtures.yml
View
@@ -0,0 +1,19 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+<% unless attributes.empty? -%>
+one:
+<% for attribute in attributes -%>
+ <%= attribute.name %>: <%= attribute.default %>
+<% end -%>
+
+two:
+<% for attribute in attributes -%>
+ <%= attribute.name %>: <%= attribute.default %>
+<% end -%>
+<% else -%>
+# one:
+# column: value
+#
+# two:
+# column: value
+<% end -%>
13 lib/generators/rspec-rails/model/templates/model_spec.rb
View
@@ -0,0 +1,13 @@
+require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper')
+
+describe <%= class_name %> do
+ before(:each) do
+ @valid_attributes = {
+ <%= attributes.map{ |a| ":#{a.name} => #{a.default.inspect}" }.join(",\n ") %>
+ }
+ end
+
+ it "should create a new instance given valid attributes" do
+ <%= class_name %>.create!(@valid_attributes)
+ end
+end
12 lib/generators/rspec-rails/observer/observer_generator.rb
View
@@ -0,0 +1,12 @@
+require 'generators/rspec'
+
+module Rspec
+ module Generators
+ class ObserverGenerator < Base
+ def create_observer_files
+ template 'observer_spec.rb',
+ File.join('spec', 'models', class_path, "#{file_name}_observer_spec.rb")
+ end
+ end
+ end
+end
5 lib/generators/rspec-rails/observer/templates/observer_spec.rb
View
@@ -0,0 +1,5 @@
+require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper')
+
+describe <%= class_name %> do
+
+end
11 lib/generators/rspec-rails/plugin/plugin_generator.rb
View
@@ -0,0 +1,11 @@
+require 'generators/rspec'
+
+module Rspec
+ module Generators
+ class PluginGenerator < Base
+ def create_spec_files
+ directory '.', 'spec'
+ end
+ end
+ end
+end
5 lib/generators/rspec-rails/plugin/templates/%file_name%_spec.rb.tt
View
@@ -0,0 +1,5 @@
+require File.expand_path(File.join(File.dirname(__FILE__), 'spec_helper.rb'))
+
+describe <%= class_name %> do
+
+end
5 lib/generators/rspec-rails/plugin/templates/test_helper.rb
View
@@ -0,0 +1,5 @@
+$TESTING=true
+$:.unshift File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
+
+Spec::Runner.configure do |config|
+end
112 lib/generators/rspec-rails/scaffold/scaffold_generator.rb
View
@@ -0,0 +1,112 @@
+require 'generators/rspec'
+require 'generators/resource_helpers'
+
+module Rspec
+ module Generators
+ class ScaffoldGenerator < Base
+ include Rails::Generators::ResourceHelpers
+ argument :attributes, :type => :array, :default => [], :banner => "field:type field:type"
+
+ class_option :orm, :desc => "ORM used to generate the controller"
+ class_option :template_engine, :desc => "Template engine to generate view files"
+ class_option :singleton, :type => :boolean, :desc => "Supply to create a singleton controller"
+
+ class_option :views, :type => :boolean, :default => true
+ class_option :routes, :type => :boolean, :default => true
+
+ def copy_controller_files
+ template 'controller_spec.rb',
+ File.join('spec/controllers', controller_class_path, "#{controller_file_name}_controller_spec.rb")
+ end
+
+ def copy_view_files
+ return unless options[:views]
+
+ copy_view :edit
+ copy_view :index unless options[:singleton]
+ copy_view :new
+ copy_view :show
+ end
+
+ def copy_routing_files
+ return unless options[:routes]
+
+ template 'routing_spec.rb',
+ File.join('spec/routing', controller_class_path, "#{controller_file_name}_routing_spec.rb")
+ end
+
+ hook_for :integration_tool, :as => :integration
+
+ protected
+
+ def copy_view(view)
+ template "#{view}_spec.rb",
+ File.join("spec/views", controller_file_path, "#{view}.html.#{options[:template_engine]}_spec.rb")
+ end
+
+ def params
+ "{'these' => 'params'}"
+ end
+
+ # Returns the name of the mock. For example, if the file name is user,
+ # it returns mock_user.
+ #
+ # If a hash is given, it uses the hash key as the ORM method and the
+ # value as response. So, for ActiveRecord and file name "User":
+ #
+ # mock_file_name(:save => true)
+ # #=> mock_user(:save => true)
+ #
+ # If another ORM is being used and another method instead of save is
+ # called, it will be the one used.
+ #
+ def mock_file_name(hash=nil)
+ if hash
+ method, and_return = hash.to_a.first
+ method = orm_instance.send(method).split('.').last.gsub(/\(.*?\)/, '')
+ "mock_#{file_name}(:#{method} => #{and_return})"
+ else
+ "mock_#{file_name}"
+ end
+ end
+
+ # Receives the ORM chain and convert to expects. For ActiveRecord:
+ #
+ # should! orm_class.find(User, "37")
+ # #=> User.should_receive(:find).with(37)
+ #
+ # For Datamapper:
+ #
+ # should! orm_class.find(User, "37")
+ # #=> User.should_receive(:get).with(37)
+ #
+ def should!(chain)
+ stub_or_should_chain(:should_receive, chain)
+ end
+
+ # Receives the ORM chain and convert to stub. For ActiveRecord:
+ #
+ # stub! orm_class.find(User, "37")
+ # #=> User.stub!(:find).with(37)
+ #
+ # For Datamapper:
+ #
+ # stub! orm_class.find(User, "37")
+ # #=> User.stub!(:get).with(37)
+ #
+ def stub!(chain)
+ stub_or_should_chain(:stub!, chain)
+ end
+
+ def stub_or_should_chain(mode, chain)
+ receiver, method = chain.split(".")
+ method.gsub!(/\((.*?)\)/, '')
+
+ response = "#{receiver}.#{mode}(:#{method})"
+ response << ".with(#{$1})" unless $1.blank?
+ response
+ end
+
+ end
+ end
+end
127 lib/generators/rspec-rails/scaffold/templates/controller_spec.rb
View
@@ -0,0 +1,127 @@
+require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper')
+
+describe <%= controller_class_name %>Controller do
+
+ def <%= mock_file_name %>(stubs={})
+ @<%= mock_file_name %> ||= mock_model(<%= class_name %>, stubs)
+ end
+
+ <% unless options[:singleton] -%>
+ describe "GET index" do
+ it "assigns all <%= table_name.pluralize %> as @<%= table_name.pluralize %>" do
+ <%= stub! orm_class.all(class_name) %>.and_return([<%= mock_file_name %>])
+ get :index
+ assigns[:<%= table_name %>].should == [<%= mock_file_name %>]
+ end
+ end
+ <% end -%>
+
+ describe "GET show" do
+ it "assigns the requested <%= file_name %> as @<%= file_name %>" do
+ <%= stub! orm_class.find(class_name, "37".inspect) %>.and_return(<%= mock_file_name %>)
+ get :show, :id => "37"
+ assigns[:<%= file_name %>].should equal(<%= mock_file_name %>)
+ end
+ end
+
+ describe "GET new" do
+ it "assigns a new <%= file_name %> as @<%= file_name %>" do
+ <%= stub! orm_class.build(class_name) %>.and_return(<%= mock_file_name %>)
+ get :new
+ assigns[:<%= file_name %>].should equal(<%= mock_file_name %>)
+ end
+ end
+
+ describe "GET edit" do
+ it "assigns the requested <%= file_name %> as @<%= file_name %>" do
+ <%= stub! orm_class.find(class_name, "37".inspect) %>.and_return(<%= mock_file_name %>)
+ get :edit, :id => "37"
+ assigns[:<%= file_name %>].should equal(<%= mock_file_name %>)
+ end
+ end
+
+ describe "POST create" do
+
+ describe "with valid params" do
+ it "assigns a newly created <%= file_name %> as @<%= file_name %>" do
+ <%= stub! orm_class.build(class_name, params) %>.and_return(<%= mock_file_name(:save => true) %>)
+ post :create, :<%= file_name %> => <%= params %>
+ assigns[:<%= file_name %>].should equal(<%= mock_file_name %>)
+ end
+
+ it "redirects to the created <%= file_name %>" do
+ <%= stub! orm_class.build(class_name) %>.and_return(<%= mock_file_name(:save => true) %>)
+ post :create, :<%= file_name %> => {}
+ response.should redirect_to(<%= table_name.singularize %>_url(<%= mock_file_name %>))
+ end
+ end
+
+ describe "with invalid params" do
+ it "assigns a newly created but unsaved <%= file_name %> as @<%= file_name %>" do
+ <%= stub! orm_class.build(class_name, params) %>.and_return(<%= mock_file_name(:save => false) %>)
+ post :create, :<%= file_name %> => <%= params %>
+ assigns[:<%= file_name %>].should equal(<%= mock_file_name %>)
+ end
+
+ it "re-renders the 'new' template" do
+ <%= stub! orm_class.build(class_name) %>.and_return(<%= mock_file_name(:save => false) %>)
+ post :create, :<%= file_name %> => {}
+ response.should render_template('new')
+ end
+ end
+
+ end
+
+ describe "PUT update" do
+
+ describe "with valid params" do
+ it "updates the requested <%= file_name %>" do
+ <%= should! orm_class.find(class_name, "37".inspect) %>.and_return(<%= mock_file_name %>)
+ mock_<%= should! orm_instance.update_attributes(params) %>
+ put :update, :id => "37", :<%= file_name %> => <%= params %>
+ end
+
+ it "assigns the requested <%= file_name %> as @<%= file_name %>" do
+ <%= stub! orm_class.find(class_name) %>.and_return(<%= mock_file_name(:update_attributes => true) %>)
+ put :update, :id => "1"
+ assigns[:<%= file_name %>].should equal(<%= mock_file_name %>)
+ end
+
+ it "redirects to the <%= file_name %>" do
+ <%= stub! orm_class.find(class_name) %>.and_return(<%= mock_file_name(:update_attributes => true) %>)
+ put :update, :id => "1"
+ response.should redirect_to(<%= table_name.singularize %>_url(<%= mock_file_name %>))
+ end
+ end
+
+ describe "with invalid params" do
+ it "assigns the <%= file_name %> as @<%= file_name %>" do
+ <%= stub! orm_class.find(class_name) %>.and_return(<%= mock_file_name(:update_attributes => false) %>)
+ put :update, :id => "1"
+ assigns[:<%= file_name %>].should equal(<%= mock_file_name %>)
+ end
+
+ it "re-renders the 'edit' template" do
+ <%= stub! orm_class.find(class_name) %>.and_return(<%= mock_file_name(:update_attributes => false) %>)
+ put :update, :id => "1"
+ response.should render_template('edit')
+ end
+ end
+
+ end
+
+ describe "DELETE destroy" do
+ it "destroys the requested <%= file_name %>" do
+ <%= should! orm_class.find(class_name, "37".inspect) %>.and_return(<%= mock_file_name %>)
+ mock_<%= should! orm_instance.destroy %>
+ delete :destroy, :id => "37"
+ end
+
+ it "redirects to the <%= table_name %> list" do
+ <%= stub! orm_class.find(class_name) %>.and_return(<%= mock_file_name(:destroy => true) %>)
+ delete :destroy, :id => "1"
+ response.should redirect_to(<%= table_name %>_url)
+ end
+ end
+
+end
25 lib/generators/rspec-rails/scaffold/templates/edit_spec.rb
View
@@ -0,0 +1,25 @@
+require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../../spec_helper')
+
+<% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%>
+describe "/<%= table_name %>/edit.html.<%= options[:template_engine] %>" do
+ include <%= controller_class_name %>Helper
+
+ before(:each) do
+ assigns[:<%= file_name %>] = @<%= file_name %> = stub_model(<%= class_name %>,
+ :new_record? => false<%= output_attributes.empty? ? '' : ',' %>
+<% output_attributes.each_with_index do |attribute, attribute_index| -%>
+ :<%= attribute.name %> => <%= attribute.default.inspect %><%= attribute_index == output_attributes.length - 1 ? '' : ','%>
+<% end -%>
+ )
+ end
+
+ it "renders the edit <%= file_name %> form" do
+ render
+
+ response.should have_tag("form[action=#{<%= file_name %>_path(@<%= file_name %>)}][method=post]") do
+<% for attribute in output_attributes -%>
+ with_tag('<%= attribute.input_type -%>#<%= file_name %>_<%= attribute.name %>[name=?]', "<%= file_name %>[<%= attribute.name %>]")
+<% end -%>
+ end
+ end
+end
27 lib/generators/rspec-rails/scaffold/templates/index_spec.rb
View
@@ -0,0 +1,27 @@
+require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../../spec_helper')
+
+<% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%>
+describe "/<%= table_name %>/index.html.<%= options[:template_engine] %>" do
+ include <%= controller_class_name %>Helper
+
+ before(:each) do
+ assigns[:<%= table_name %>] = [
+<% [1,2].each_with_index do |id, model_index| -%>
+ stub_model(<%= class_name %><%= output_attributes.empty? ? (model_index == 1 ? ')' : '),') : ',' %>
+<% output_attributes.each_with_index do |attribute, attribute_index| -%>
+ :<%= attribute.name %> => <%= attribute.default.inspect %><%= attribute_index == output_attributes.length - 1 ? '' : ','%>
+<% end -%>
+<% if !output_attributes.empty? -%>
+ <%= model_index == 1 ? ')' : '),' %>
+<% end -%>
+<% end -%>
+ ]
+ end
+
+ it "renders a list of <%= table_name %>" do
+ render
+<% for attribute in output_attributes -%>
+ response.should have_tag("tr>td", <%= attribute.default.inspect %>.to_s, 2)
+<% end -%>
+ end
+end
25 lib/generators/rspec-rails/scaffold/templates/new_spec.rb
View
@@ -0,0 +1,25 @@
+require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../../spec_helper')
+
+<% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%>
+describe "/<%= table_name %>/new.html.<%= options[:template_engine] %>" do
+ include <%= controller_class_name %>Helper
+
+ before(:each) do
+ assigns[:<%= file_name %>] = stub_model(<%= class_name %>,
+ :new_record? => true<%= output_attributes.empty? ? '' : ',' %>
+<% output_attributes.each_with_index do |attribute, attribute_index| -%>
+ :<%= attribute.name %> => <%= attribute.default.inspect %><%= attribute_index == output_attributes.length - 1 ? '' : ','%>
+<% end -%>
+ )
+ end
+
+ it "renders new <%= file_name %> form" do
+ render
+
+ response.should have_tag("form[action=?][method=post]", <%= table_name %>_path) do
+<% for attribute in output_attributes -%>
+ with_tag("<%= attribute.input_type -%>#<%= file_name %>_<%= attribute.name %>[name=?]", "<%= file_name %>[<%= attribute.name %>]")
+<% end -%>
+ end
+ end
+end
67 lib/generators/rspec-rails/scaffold/templates/routing_spec.rb
View
@@ -0,0 +1,67 @@
+require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper')
+
+describe <%= controller_class_name %>Controller do
+ describe "route generation" do
+ <% unless options[:singleton] -%>
+ it "maps #index" do
+ route_for(:controller => "<%= table_name %>", :action => "index").should == "/<%= table_name %>"
+ end
+ <% end -%>
+
+ it "maps #new" do
+ route_for(:controller => "<%= table_name %>", :action => "new").should == "/<%= table_name %>/new"
+ end
+
+ it "maps #show" do
+ route_for(:controller => "<%= table_name %>", :action => "show", :id => "1").should == "/<%= table_name %>/1"
+ end
+
+ it "maps #edit" do
+ route_for(:controller => "<%= table_name %>", :action => "edit", :id => "1").should == "/<%= table_name %>/1/edit"
+ end
+
+ it "maps #create" do
+ route_for(:controller => "<%= table_name %>", :action => "create").should == {:path => "/<%= table_name %>", :method => :post}
+ end
+
+ it "maps #update" do
+ route_for(:controller => "<%= table_name %>", :action => "update", :id => "1").should == {:path =>"/<%= table_name %>/1", :method => :put}
+ end
+
+ it "maps #destroy" do
+ route_for(:controller => "<%= table_name %>", :action => "destroy", :id => "1").should == {:path =>"/<%= table_name %>/1", :method => :delete}
+ end
+ end
+
+ describe "route recognition" do
+ <% unless options[:singleton] -%>
+ it "generates params for #index" do
+ params_from(:get, "/<%= table_name %>").should == {:controller => "<%= table_name %>", :action => "index"}
+ end
+ <% end -%>
+
+ it "generates params for #new" do
+ params_from(:get, "/<%= table_name %>/new").should == {:controller => "<%= table_name %>", :action => "new"}
+ end
+
+ it "generates params for #create" do
+ params_from(:post, "/<%= table_name %>").should == {:controller => "<%= table_name %>", :action => "create"}
+ end
+
+ it "generates params for #show" do
+ params_from(:get, "/<%= table_name %>/1").should == {:controller => "<%= table_name %>", :action => "show", :id => "1"}
+ end
+
+ it "generates params for #edit" do
+ params_from(:get, "/<%= table_name %>/1/edit").should == {:controller => "<%= table_name %>", :action => "edit", :id => "1"}
+ end
+
+ it "generates params for #update" do
+ params_from(:put, "/<%= table_name %>/1").should == {:controller => "<%= table_name %>", :action => "update", :id => "1"}
+ end
+
+ it "generates params for #destroy" do
+ params_from(:delete, "/<%= table_name %>/1").should == {:controller => "<%= table_name %>", :action => "destroy", :id => "1"}
+ end
+ end
+end
22 lib/generators/rspec-rails/scaffold/templates/show_spec.rb
View
@@ -0,0 +1,22 @@
+require File.expand_path(File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../../spec_helper')
+
+<% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%>
+describe "/<%= table_name %>/show.html.<%= options[:template_engine] %>" do
+ include <%= controller_class_name %>Helper
+ before(:each) do
+ assigns[:<%= file_name %>] = @<%= file_name %> = stub_model(<%= class_name %><%= output_attributes.empty? ? ')' : ',' %>
+<% output_attributes.each_with_index do |attribute, attribute_index| -%>
+ :<%= attribute.name %> => <%= attribute.default.inspect %><%= attribute_index == output_attributes.length - 1 ? '' : ','%>
+<% end -%>
+<% if !output_attributes.empty? -%>
+ )
+<% end -%>
+ end
+
+ it "renders attributes in <p>" do
+ render
+<% for attribute in output_attributes -%>
+ response.should have_text(/<%= Regexp.escape(attribute.default.inspect).gsub(/^"|"$/, '')%>/)
+<% end -%>
+ end
+end
36 lib/rspec/rails/example/controller_example_group.rb
View
@@ -1,6 +1,38 @@
-require 'rspec/rails/core/example/controller_example_group'
+require 'action_dispatch'
module ControllerExampleGroupBehaviour
- # add factory_girl
+ include ActionDispatch::Assertions
+ include ActionDispatch::Integration::Runner
+
+ def self.included(mod)
+ mod.before { @_result = Struct.new(:add_assertion).new }
+ end
+
+ def app
+ self.class.described_class.action(@_action)
+ end
+
+ %w[get post put delete head].map do |method|
+ eval <<-CODE
+ def #{method}(action)
+ @_action = action
+ super '/'
+ end
+ CODE
+ end
+
+ Rspec::Core.configure do |c|
+ c.include self, :behaviour => { :describes => lambda {|c| c < ::ActionController::Base} }
+ end
end
+
+# describe WidgetsController do
+ # context "GET index" do
+ # it "does something" do
+ # get :index
+ # response.body.should == "this text"
+ # end
+ # end
+# end
+
15 lib/rspec/rails/example/request_example_group.rb
View
@@ -1,11 +1,16 @@
-require 'rspec/rails/core/example/request_example_group'
+require 'action_dispatch'
require 'webrat'
module RequestExampleGroupBehaviour
+ include ActionDispatch::Assertions
+ include ActionDispatch::Integration::Runner
include Webrat::Matchers
include Webrat::Methods
+ Rails.application.routes.install_helpers(self)
- # add factory_girl
+ def app
+ Rails.application
+ end
Webrat.configure do |config|
config.mode = :rack
@@ -14,6 +19,11 @@ module RequestExampleGroupBehaviour
def last_response
response
end
+
+ Rspec::Core.configure do |c|
+ c.include self
+ # , :behaviour => { :describes => /^\// }
+ end
end
# describe "/widgets" do
@@ -26,3 +36,4 @@ def last_response
# end
# end
# end
+
Please sign in to comment.
Something went wrong with that request. Please try again.