pax_global_header00006660000000000000000000000064121460420000014477gustar00rootroot0000000000000052 comment=55bfd60a3ee74a757af19116bbe10674d4654bea rspec-rails-2.13.2/000077500000000000000000000000001214604200000140105ustar00rootroot00000000000000rspec-rails-2.13.2/.document000066400000000000000000000000611214604200000156240ustar00rootroot00000000000000lib/**/*.rb - README.md License.txt Changelog.md rspec-rails-2.13.2/.gitignore000066400000000000000000000002261214604200000160000ustar00rootroot00000000000000tmp doc pkg vendor !lib/rspec/rails/vendor *.gem Gemfile.lock bin .rvmrc *.rbc .yardoc .bundle .rails-version .DS_Store Gemfile-custom .rbenv-version rspec-rails-2.13.2/.rspec000066400000000000000000000000101214604200000151140ustar00rootroot00000000000000--color rspec-rails-2.13.2/.travis.yml000066400000000000000000000021501214604200000161170ustar00rootroot00000000000000script: "bin/rake --trace 2>&1" bundler_args: "--binstubs --without documentation" before_install: gem install bundler rvm: - 1.8.7 - 1.9.2 - 1.9.3 - 2.0.0 env: - RAILS_VERSION=4.0.0.rc1 - RAILS_VERSION=3.2.13 - RAILS_VERSION=3.1.12 - RAILS_VERSION=3.0.20 - RAILS_VERSION=4-0-stable - RAILS_VERSION=3-2-stable - RAILS_VERSION=3-1-stable - RAILS_VERSION=3-0-stable - RAILS_VERSION=master matrix: exclude: # 3.0.x is not supported on MRI 2.0.0 - rvm: 2.0.0 env: RAILS_VERSION=3.0.20 - rvm: 2.0.0 env: RAILS_VERSION=3-0-stable # 4.0.x is not supported on MRI 1.8.7 or 1.9.2 - rvm: 1.8.7 env: RAILS_VERSION=master - rvm: 1.9.2 env: RAILS_VERSION=master - rvm: 1.8.7 env: RAILS_VERSION=4-0-stable - rvm: 1.9.2 env: RAILS_VERSION=4-0-stable - rvm: 1.8.7 env: RAILS_VERSION=4.0.0.rc1 - rvm: 1.9.2 env: RAILS_VERSION=4.0.0.rc1 allow_failures: - env: RAILS_VERSION=master - env: RAILS_VERSION=4.0.0.rc1 - env: RAILS_VERSION=3-2-stable - env: RAILS_VERSION=3-1-stable - env: RAILS_VERSION=3-0-stable rspec-rails-2.13.2/.yardopts000066400000000000000000000002361214604200000156570ustar00rootroot00000000000000--no-private --exclude features --exclude lib/generators/**/*_spec.rb --markup markdown --template-path yard/template/ - Changelog.md License.txt Capybara.md rspec-rails-2.13.2/Capybara.md000066400000000000000000000042411214604200000160550ustar00rootroot00000000000000rspec-rails supports integration with Capbyara out of the box by adding its Capybara::DSL (visit/page) and Capybara::RSpecMatchers to the examples in the applicable directories, which differ slightly between Capybara 1.x and Capybara >= 2.x. ## Capybara::DSL Adds the `visit` and `page` methods, which work together to simulate a GET request and provide access to the result (via `page`). ## Capybara::RSpecMatchers Exposes matchers used to specify expected HTML content (e.g. `should_not have_selector` will work correctly). ## Capybara 1.x Capybara::DSL is added to examples in: * spec/requests # included by Capybara * spec/controllers Capybara::RSpecMatchers is added to examples in: * spec/requests # included by Capybara * spec/controllers * spec/views * spec/helpers * spec/mailers ## Capybara 2.0 To use Capybara 2.0, you need rspec-rails-2.11.1 or greater. Capybara::DSL is added to examples in: * spec/features Capybara::RSpecMatchers is added to examples in: * spec/features * spec/controllers * spec/views * spec/helpers * spec/mailers ## Upgrading to Capybara-2.0 Many users have been confused by the co-existence of the the Capybara::DSL (visit/page) alongside the rack-test DSL (get|post|put|delete|head/response.body) in examples in spec/requests and spec/controllers. As of rspec-rails-2.11.1 and capybara-2.0.0.beta2, these are separated as follows: * Capybara::DSL is included `spec/features` * rack-test DSL is included in `spec/requests` and `spec/controllers` Capybara::RSpecMatchers is added to examples in: * spec/features * spec/controllers * spec/views * spec/helpers * spec/mailers If you're upgrading to Capybara-2.0 and you used visit/page in spec/requests you'll want to move those examples to spec/features and they should just work. If you want to leave those examples in spec/requests, you can include Capybara::DSL in those examples yourself as follows, but this is absolutely not recommended as you will be overriding the intended behavior and accepting the risks associated with doing so: # not recommended! RSpec.configure do |c| c.include Capybara::DSL, :example_group => { :file_path => "spec/requests" } end rspec-rails-2.13.2/Changelog.md000066400000000000000000000350601214604200000162250ustar00rootroot00000000000000### 2.13.2 / 2013-05-18 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.13.1...v2.13.2) Bug fixes * `let` definitions may override methods defined in modules brought in via `config.include` in controller specs. Fixes regression introduced in 2.13. (Andy Lindeman, Jon Rowe) * Code that checks Rails version numbers is more robust in cases where Rails is not fully loaded. (Andy Lindeman) ### 2.13.1 / 2013-04-27 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.13.0...v2.13.1) Bug fixes * View specs are no longer generated if no template engine is specified (Kevin Glowacz) * `ActionController::Base.allow_forgery_protection` is set to its original value after each example. (Mark Dimas) * `patch` is supported in routing specs. (Chris Your) * Routing assertions are supported in controller specs in Rails 4. (Andy Lindeman) * Fix spacing in the install generator template (Taiki ONO) ### 2.13.0 / 2013-02-23 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.12.2...v2.13.0) Enhancements * `be_valid` matcher includes validation error messages. (Tom Scott) * Adds cucumber scenario showing how to invoke an anonymous controller's non-resourceful actions. (Paulo Luis Franchini Casaretto) * Null template handler is used when views are stubbed. (Daniel Schierbeck) * The generated `spec_helper.rb` in Rails 4 includes a check for pending migrations. (Andy Lindeman) * Adds `rake spec:features` task. (itzki) * Rake tasks are automatically generated for each spec/ directory. (Rudolf Schmidt) ### 2.12.2 / 2013-01-12 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.12.1...v2.12.2) Bug fixes * Reverts earlier fix where anonymous controllers defined the `_routes` method to support testing of redirection and generation of URLs from other contexts. The implementation ended up breaking the ability to refer to non-anonymous routes in the context of the controller under test. * Uses `assert_select` correctly in view specs generated by scaffolding. (Andy Lindeman) ### 2.12.1 / 2013-01-07 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.12.0...v2.12.1) Bug fixes * Operates correctly when ActiveRecord is only partially loaded (e.g., with older versions of Mongoid). (Eric Marden) * `expect(subject).to have(...).errors_on` operates correctly for ActiveResource models where `valid?` does not accept an argument. (Yi Wen) * Rails 4 support for routing specs. (Andy Lindeman) * Rails 4 support for `ActiveRecord::Relation` and the `=~` operator matcher. (Andy Lindeman) * Anonymous controllers define `_routes` to support testing of redirection and generation of URLs from other contexts. (Andy Lindeman) ### 2.12.0 / 2012-11-12 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.11.4...v2.12.0) Enhancements * Support validation contexts when using `#errors_on` (Woody Peterson) * Include RequestExampleGroup in groups in spec/api Bug fixes * Add `should` and `should_not` to `CollectionProxy` (Rails 3.1+) and `AssociationProxy` (Rails 3.0). (Myron Marston) * `controller.controller_path` is set correctly for view specs in Rails 3.1+. (Andy Lindeman) * Generated specs support module namespacing (e.g., in a Rails engine). (Andy Lindeman) * `render` properly infers the view to be rendered in Rails 3.0 and 3.1 (John Firebaugh) * AutoTest mappings involving config/ work correctly (Brent J. Nordquist) * Failures message for `be_new_record` are more useful (Andy Lindeman) ### 2.11.4 / 2012-10-14 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.11.0...v2.11.4) Capybara-2.0 integration support: * include RailsExampleGroup in spec/features (necessary when there is no AR) * include Capybara::DSL and Capybara::RSpecMatchers in spec/features See [https://github.com/jnicklas/capybara/pull/809](https://github.com/jnicklas/capybara/pull/809) and [http://rubydoc.info/gems/rspec-rails/file/Capybara.md](http://rubydoc.info/gems/rspec-rails/file/Capybara.md) for background. 2.11.1, .2, .3 were yanked due to errant documentation. ### 2.11.0 / 2012-07-07 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.10.1...v2.11.0) Enhancements * The generated `spec/spec_helper.rb` sets `config.order = "random"` so that specs run in random order by default. * rename `render_template` to `have_rendered` (and alias to `render_template` for backward compatibility) * The controller spec generated with `rails generate scaffold namespaced::model` matches the spec generated with `rails generate scaffold namespaced/model` (Kohei Hasegawa) Bug fixes * "uninitialized constant" errors are avoided when using using gems like `rspec-rails-uncommitted` that define `Rspec::Rails` before `rspec-rails` loads (Andy Lindeman) ### 2.10.1 / 2012-05-03 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.10.0...v2.10.1) Bug fixes * fix regression introduced in 2.10.0 that broke integration with Devise (https://github.com/rspec/rspec-rails/issues/534) * remove generation of helper specs when running the scaffold generator, as Rails already does this (Jack Dempsey) ### 2.10.0 / 2012-05-03 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.9.0...v2.10.0) Bug fixes * `render_views` called in a spec can now override the config setting. (martinsvalin) * Fix `render_views` for anonymous controllers on 1.8.7. (hudge, mudge) * Eliminate use of deprecated `process_view_paths` * Fix false negatives when using `route_to` matcher with `should_not` * `controller` is no longer nil in `config.before` hooks * Change `request.path_parameters` keys to symbols to match real Rails environment (Nathan Broadbent) * Silence deprecation warnings in pre-2.9 generated view specs (Jonathan del Strother) ### 2.9.0 / 2012-03-17 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.8.1...v2.9.0) Enhancements * add description method to RouteToMatcher (John Wulff) * Run "db:test:clone_structure" instead of "db:test:prepare" if Active Record's schema format is ":sql". (Andrey Voronkov) Bug fixes * `mock_model(XXX).as_null_object.unknown_method` returns self again * Generated view specs use different IDs for each attribute. ### 2.8.1 / 2012-01-04 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.8.0...v2.8.1) NOTE: there was a change in rails-3.2.0.rc2 which broke compatibility with stub_model in rspec-rails. This release fixes that issue, but it means that you'll have to upgrade to rspec-rails-2.8.1 when you upgrade to rails >= 3.2.0.rc2. * Bug fixes * Explicitly stub valid? in stub_model. Fixes stub_model for rails versions >= 3.2.0.rc2. ### 2.8.0 / 2012-01-04 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.8.0.rc2...v2.8.0) * Enhancements * Eliminate deprecation warnings in generated view specs in Rails 3.2 * Ensure namespaced helpers are included automatically (Evgeniy Dolzhenko) * Added cuke scenario documenting which routes are generated for anonymous controllers (Alan Shields) ### 2.8.0.rc2 / 2011-12-19 [full changelog](http://github.com/rspec/rspec-mocks/compare/v2.8.0.rc1...v2.8.0.rc2) * Enhancements * Add session hash to generated controller specs (Thiago Almeida) * Eliminate deprecation warnings about InstanceMethods modules in Rails 3.2 * Bug fixes * Stub attribute accessor after `respond_to?` call on mocked model (Igor Afonov) ### 2.8.0.rc1 / 2011-11-06 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.7.0...v2.8.0.rc1) * Enhancements * Removed unnecessary "config.mock_with :rspec" from spec_helper.rb (Paul Annesley) * Changes * No API changes for rspec-rails in this release, but some internals changed to align with rspec-core-2.8 * [rspec-core](https://github.com/rspec/rspec-core/blob/master/Changelog.md) * [rspec-expectations](https://github.com/rspec/rspec-expectations/blob/master/Changelog.md) * [rspec-mocks](https://github.com/rspec/rspec-mocks/blob/master/Changelog.md) ### 2.7.0 / 2011-10-16 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.6.1...v2.7.0) * Enhancements * `ActiveRecord::Relation` can use the `=~` matcher (Andy Lindeman) * Make generated controller spec more consistent with regard to ids (Brent J. Nordquist) * Less restrictive autotest mapping between spec and implementation files (José Valim) * `require 'rspec/autorun'` from generated `spec_helper.rb` (David Chelimsky) * add `bypass_rescue` (Lenny Marks) * `route_to` accepts query string (Marc Weil) * Internal * Added specs for generators using ammeter (Alex Rothenberg) * Bug fixes * Fix configuration/integration bug with rails 3.0 (fixed in 3.1) in which `fixure_file_upload` reads from `ActiveSupport::TestCase.fixture_path` and misses RSpec's configuration (David Chelimsky) * Support nested resource in view spec generator (David Chelimsky) * Define `primary_key` on class generated by `mock_model("WithAString")` (David Chelimsky) ### 2.6.1 / 2011-05-25 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.6.0...v2.6.1) This release is compatible with rails-3.1.0.rc1, but not rails-3.1.0.beta1 * Bug fixes * fix controller specs with anonymous controllers with around filters * exclude spec directory from rcov metrics (Rodrigo Navarro) * guard against calling prerequisites on nil default rake task (Jack Dempsey) ### 2.6.0 / 2011-05-12 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.5.0...v2.6.0) * Enhancements * rails 3 shortcuts for routing specs (Joe Fiorini) * support nested resources in generators (Tim McEwan) * require 'rspec/rails/mocks' to use `mock_model` without requiring the whole rails framework * Update the controller spec generated by the rails scaffold generator: * Add documentation to the generated spec * Use `any_instance` to avoid stubbing finders * Use real objects instead of `mock_model` * Update capybara integration to work with capy 0.4 and 1.0.0.beta * Decorate paths passed to `[append|prepend]_view_paths` with empty templates unless rendering views. (Mark Turner) * Bug fixes * fix typo in "rake spec:statsetup" (Curtis Schofield) * expose named routes in anonymous controller specs (Andy Lindeman) * error when generating namespaced scaffold resources (Andy Lindeman) * Fix load order issue w/ Capybara (oleg dashevskii) * Fix monkey patches that broke due to internal changes in rails-3.1.0.beta1 ### 2.5.0 / 2011-02-05 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.4.1...v2.5.0) * Enhancements * use index_helper instead of table_name when generating specs (Reza Primardiansyah) * Bug fixes * fixed bug in which `render_views` in a nested group set the value in its parent group. * only include MailerExampleGroup when it is defined (Steve Sloan) * mock_model.as_null_object.attribute.blank? returns false (Randy Schmidt) * fix typo in request specs (Paco Guzman) ### 2.4.1 / 2011-01-03 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.4.0...v2.4.1) * Bug fixes * fixed bug caused by including some Rails modules before RSpec's RailsExampleGroup ### 2.4.0 / 2011-01-02 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.3.1...v2.4.0) * Enhancements * include ApplicationHelper in helper object in helper specs * include request spec extensions in files in spec/integration * include controller spec extensions in groups that use :type => :controller * same for :model, :view, :helper, :mailer, :request, :routing * Bug fixes * restore global config.render_views so you only need to say it once * support overriding render_views in nested groups * matchers that delegate to Rails' assertions capture ActiveSupport::TestCase::Assertion (so they work properly now with should_not in Ruby 1.8.7 and 1.9.1) * Deprecations * include_self_when_dir_matches ### 2.3.1 / 2010-12-16 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.3.0...v2.3.1) * Bug fixes * respond_to? correctly handles 2 args * scaffold generator no longer fails on autotest directory ### 2.3.0 / 2010-12-12 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.2.1...v2.3.0) * Changes * Generator no longer generates autotest/autodiscover.rb, as it is no longer needed (as of rspec-core-2.3.0) ### 2.2.1 / 2010-12-01 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.2.0...v2.2.1) * Bug fixes * Depend on railties, activesupport, and actionpack instead of rails (Piotr Solnica) * Got webrat integration working properly across different types of specs * Deprecations * --webrat-matchers flag for generators is deprecated. use --webrat instead. ### 2.2.0 / 2010-11-28 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.1.0...v2.2.0) * Enhancements * Added stub_template in view specs * Bug fixes * Properly include helpers in views (Jonathan del Strother) * Fix bug in which method missing led to a stack overflow * Fix stack overflow in request specs with open_session * Fix stack overflow in any spec when method_missing was invoked * Add gem dependency on rails ~> 3.0.0 (ensures bundler won't install rspec-rails-2 with rails-2 apps). ### 2.1.0 / 2010-11-07 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.0.1...v2.1.0) * Enhancements * Move errors_on to ActiveModel to support other AM-compliant ORMs * Bug fixes * Check for presence of ActiveRecord instead of checking Rails config (gets rspec out of the way of multiple ORMs in the same app) ### 2.0.1 / 2010-10-15 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.0.0...v2.0.1) * Enhancements * Add option to not generate request spec (--skip-request-specs) * Bug fixes * Updated the mock_[model] method generated in controller specs so it adds any stubs submitted each time it is called. * Fixed bug where view assigns weren't making it to the view in view specs in Rails-3.0.1. (Emanuele Vicentini) ### 2.0.0 / 2010-10-10 [full changelog](https://github.com/rspec/rspec-rails/compare/ea6bdef...v2.0.0) * Enhancements * ControllerExampleGroup uses controller as the implicit subject by default (Paul Rosania) * autotest mapping improvements (Andreas Neuhaus) * more cucumber features (Justin Ko) * clean up spec helper (Andre Arko) * add assign(name, value) to helper specs (Justin Ko) * stub_model supports primary keys other than id (Justin Ko) * support choice between Webrat/Capybara (Justin Ko) * support specs for 'abstract' subclasses of ActionController::Base (Mike Gehard) * be_a_new matcher supports args (Justin Ko) * Bug fixes * support T::U components in mailer and request specs (Brasten Sager) rspec-rails-2.13.2/DEV-README.md000066400000000000000000000014431214604200000157050ustar00rootroot00000000000000## Set up the dev environment git clone git://github.com/rspec/rspec-rails.git cd rspec-rails gem install bundler bundle install --binstubs Now you should be able to run any of: bin/rake bin/rake spec bin/rake cucumber ## Rails version rspec-rails runs its tests against many versions of Rails. To switch the active version used for tests, use the `thor version:use` command. Examples: thor version:use 3.2.8 thor version:use 3-2-stable thor version:use master ## Customize the dev enviroment The Gemfile includes the gems you'll need to be able to run specs. If you want to customize your dev enviroment with additional tools like guard or ruby-debug, add any additional gem declarations to Gemfile-custom (see Gemfile-custom.sample for some examples). rspec-rails-2.13.2/Gemfile000066400000000000000000000032221214604200000153020ustar00rootroot00000000000000source "https://rubygems.org" gemspec %w[rspec rspec-core rspec-expectations rspec-mocks].each do |lib| library_path = File.expand_path("../../#{lib}", __FILE__) if File.exist?(library_path) gem lib, :path => library_path elsif ENV["CI"] || ENV["USE_GIT_REPOS"] gem lib, :git => "git://github.com/rspec/#{lib}.git" else gem lib end end ### deps for rdoc.info group :documentation do gem 'yard', '0.8.0', :require => false gem 'redcarpet', '2.1.1' gem 'github-markup', '0.7.2' end platforms :jruby do gem "jruby-openssl" end gem 'sqlite3', '~> 1.3.6' # Capybara 2.1 requires Ruby >= 1.9.3 if RUBY_VERSION < '1.9.3' gem 'capybara', '>= 2.0.0', '< 2.1.0' end custom_gemfile = File.expand_path("../Gemfile-custom", __FILE__) eval File.read(custom_gemfile) if File.exist?(custom_gemfile) version_file = File.expand_path("../.rails-version", __FILE__) case version = ENV['RAILS_VERSION'] || (File.exist?(version_file) && File.read(version_file).chomp) when /master/ gem "rails", :git => "git://github.com/rails/rails.git" gem "arel", :git => "git://github.com/rails/arel.git" gem "journey", :git => "git://github.com/rails/journey.git" gem "activerecord-deprecated_finders", :git => "git://github.com/rails/activerecord-deprecated_finders.git" gem "rails-observers", :git => "git://github.com/rails/rails-observers" gem 'sass-rails', :git => "git://github.com/rails/sass-rails.git" gem 'coffee-rails', :git => "git://github.com/rails/coffee-rails.git" when /stable$/ gem "rails", :git => "git://github.com/rails/rails.git", :branch => version when nil, false, "" gem "rails", "3.2.13" else gem "rails", version end rspec-rails-2.13.2/Gemfile-custom.sample000066400000000000000000000005441214604200000200760ustar00rootroot00000000000000group :development do gem 'interactive_rspec' gem 'relish', '~> 0.6.0' gem 'guard-rspec', '~> 1.2.1' gem 'growl', '1.0.3' gem 'spork', '0.9.0' platform :mri do gem 'rb-fsevent', '~> 0.9.0' gem 'ruby-prof', '~> 0.10.0' case RUBY_VERSION when /^1.8/ gem 'ruby-debug' when /^1.9/ gem 'debugger' end end end rspec-rails-2.13.2/History.md000066400000000000000000000000321214604200000157660ustar00rootroot00000000000000See features/Changelog.md rspec-rails-2.13.2/License.txt000066400000000000000000000021221214604200000161300ustar00rootroot00000000000000(The MIT License) Copyright (c) 2006 David Chelimsky, The RSpec Development Team Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. rspec-rails-2.13.2/README.md000066400000000000000000000277261214604200000153050ustar00rootroot00000000000000# rspec-rails [![Build Status](https://secure.travis-ci.org/rspec/rspec-rails.png?branch=master)](http://travis-ci.org/rspec/rspec-rails) [![Code Climate](https://codeclimate.com/github/rspec/rspec-rails.png)](https://codeclimate.com/github/rspec/rspec-rails) **rspec-rails** is a testing framework for Rails 3.x and 4.x. Use **[rspec-rails 1.x](http://github.com/dchelimsky/rspec-rails)** for Rails 2.x. ## Installation Add `rspec-rails` to **both** the `:development` and `:test` groups in the `Gemfile`: ```ruby group :development, :test do gem 'rspec-rails', '~> 2.0' end ``` Download and install by running: ``` bundle install ``` Initialize the `spec/` directory (where specs will reside) with: ``` rails generate rspec:install ``` To run your specs, use the `rspec` command: ``` bundle exec rspec # Run only model specs bundle exec rspec spec/models # Run only specs for AccountsController bundle exec rspec spec/controllers/accounts_controller_spec.rb ``` Specs can also be run via `rake spec`, though this command may be slower to start than the `rspec` command. In Rails 4, you may want to create a binstub for the `rspec` command so it can be run via `bin/rspec`: ``` bundle binstubs rspec-core ``` ### Generators Once installed, RSpec will generate spec files instead of Test::Unit test files when commands like `rails generate model` and `rails generate controller` are used. ## Model Specs Model specs reside in the `spec/models` folder. Use model specs to describe behavior of models (usually ActiveRecord-based) in the application. For example: ```ruby require "spec_helper" describe User do it "orders by last name" do lindeman = User.create!(first_name: "Andy", last_name: "Lindeman") chelimsky = User.create!(first_name: "David", last_name: "Chelimsky") expect(User.ordered_by_last_name).to eq([chelimsky, lindeman]) end end ``` For more information, see [cucumber scenarios for model specs](https://www.relishapp.com/rspec/rspec-rails/docs/model-specs). ## Controller Specs Controller specs reside in the `spec/controllers` folder. Use controller specs to describe behavior of Rails controllers. For example: ```ruby require "spec_helper" describe PostsController do describe "GET #index" do it "responds successfully with an HTTP 200 status code" do get :index expect(response).to be_success expect(response.status).to eq(200) end it "renders the index template" do get :index expect(response).to render_template("index") end it "loads all of the posts into @posts" do post1, post2 = Post.create!, Post.create! get :index expect(assigns(:posts)).to match_array([post1, post2]) end end end ``` For more information, see [cucumber scenarios for controller specs](https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs). **Note:** To encourage more isolated testing, views are not rendered by default in controller specs. If you wish to assert against the contents of the rendered view in a controller spec, enable [render\_views](https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs/render-views) or use a higher-level [request spec](#request-specs) or [feature spec](#feature-specs). ## Request Specs Request specs live in spec/requests, spec/api and spec/integration, and mix in behavior [ActionDispatch::Integration::Runner](http://api.rubyonrails.org/classes/ActionDispatch/Integration/Runner.html), which is the basis for [Rails' integration tests](http://guides.rubyonrails.org/testing.html#integration-testing). The intent is to specify one or more request/response cycles from end to end using a black box approach. ```ruby require 'spec_helper' describe "home page" do it "displays the user's username after successful login" do user = User.create!(:username => "jdoe", :password => "secret") get "/login" assert_select "form.login" do assert_select "input[name=?]", "username" assert_select "input[name=?]", "password" assert_select "input[type=?]", "submit" end post "/login", :username => "jdoe", :password => "secret" assert_select ".header .username", :text => "jdoe" end end ``` This example uses only standard Rails and RSpec API's, but many RSpec/Rails users like to use extension libraries like [FactoryGirl](https://github.com/thoughtbot/factory_girl) and [Capybara](https://github.com/jnicklas/capybara): ```ruby require 'spec_helper' describe "home page" do it "displays the user's username after successful login" do user = FactoryGirl.create(:user, :username => "jdoe", :password => "secret") visit "/login" fill_in "Username", :with => "jdoe" fill_in "Password", :with => "secret" click_button "Log in" expect(page).to have_selector(".header .username", :text => "jdoe") end end ``` FactoryGirl decouples this example from changes to validation requirements, which can be encoded into the underlying factory definition without requiring changes to this example. Among other benefits, Capybara binds the form post to the generated HTML, which means we don't need to specify them separately. Note that Capybara's DSL as shown is, by default, only available in specs in the spec/features directory. For more information, see the [Capybara integration docs](http://rubydoc.info/gems/rspec-rails/file/Capybara.md). There are several other Ruby libs that implement the factory pattern or provide a DSL for request specs (a.k.a. acceptance or integration specs), but FactoryGirl and Capybara seem to be the most widely used. Whether you choose these or other libs, we strongly recommend using something for each of these roles. # View specs View specs live in spec/views, and mix in ActionView::TestCase::Behavior. ```ruby require 'spec_helper' describe "events/index" do it "renders _event partial for each event" do assign(:events, [stub_model(Event), stub_model(Event)]) render expect(view).to render_template(:partial => "_event", :count => 2) end end describe "events/show" do it "displays the event location" do assign(:event, stub_model(Event, :location => "Chicago" )) render expect(rendered).to include("Chicago") end end ``` View specs infer the controller name and path from the path to the view template. e.g. if the template is "events/index.html.erb" then: ```ruby controller.controller_path == "events" controller.request.path_parameters[:controller] == "events" ``` This means that most of the time you don't need to set these values. When spec'ing a partial that is included across different controllers, you _may_ need to override these values before rendering the view. To provide a layout for the render, you'll need to specify _both_ the template and the layout explicitly. For example: ```ruby render :template => "events/show", :layout => "layouts/application" ``` ## `assign(key, val)` Use this to assign values to instance variables in the view: ```ruby assign(:widget, stub_model(Widget)) render ``` The code above assigns `stub_model(Widget)` to the `@widget` variable in the view, and then renders the view. Note that because view specs mix in `ActionView::TestCase` behavior, any instance variables you set will be transparently propagated into your views (similar to how instance variables you set in controller actions are made available in views). For example: ```ruby @widget = stub_model(Widget) render # @widget is available inside the view ``` RSpec doesn't officially support this pattern, which only works as a side-effect of the inclusion of `ActionView::TestCase`. Be aware that it may be made unavailable in the future. ### Upgrade note ```ruby # rspec-rails-1.x assigns[key] = value # rspec-rails-2.x assign(key, value) ``` ## `rendered` This represents the rendered view. ```ruby render expect(rendered).to match /Some text expected to appear on the page/ ``` ### Upgrade note ```ruby # rspec-rails-1.x render response.should xxx # rspec-rails-2.x render rendered.should xxx # rspec-rails-2.x with expect syntax render expect(rendered).to xxx ``` # Routing specs Routing specs live in spec/routing. ```ruby require 'spec_helper' describe "routing to profiles" do it "routes /profile/:username to profile#show for username" do expect(:get => "/profiles/jsmith").to route_to( :controller => "profiles", :action => "show", :username => "jsmith" ) end it "does not expose a list of profiles" do expect(:get => "/profiles").not_to be_routable end end ``` ### Upgrade note `route_for` from rspec-rails-1.x is gone. Use `route_to` and `be_routable` instead. # Helper specs Helper specs live in spec/helpers, and mix in ActionView::TestCase::Behavior. Provides a `helper` object which mixes in the helper module being spec'd, along with `ApplicationHelper` (if present). ```ruby require 'spec_helper' describe EventsHelper do describe "#link_to_event" do it "displays the title, and formatted date" do event = Event.new("Ruby Kaigi", Date.new(2010, 8, 27)) # helper is an instance of ActionView::Base configured with the # EventsHelper and all of Rails' built-in helpers expect(helper.link_to_event).to match /Ruby Kaigi, 27 Aug, 2010/ end end end ``` # Matchers rspec-rails exposes domain-specific matchers to each of the example group types. Most of them simply delegate to Rails' assertions. ## `be_a_new` * Available in all specs. * Primarily intended for controller specs ```ruby expect(object).to be_a_new(Widget) ``` Passes if the object is a `Widget` and returns true for `new_record?` ## `render_template` * Delegates to Rails' assert_template. * Available in request, controller, and view specs. In request and controller specs, apply to the response object: ```ruby expect(response).to render_template("new") ``` In view specs, apply to the view object: ```ruby expect(view).to render_template(:partial => "_form", :locals => { :widget => widget } ) ``` ## `redirect_to` * Delegates to assert_redirect * Available in request and controller specs. ```ruby expect(response).to redirect_to(widgets_path) ``` ## `route_to` * Delegates to Rails' assert_routing. * Available in routing and controller specs. ```ruby expect(:get => "/widgets").to route_to(:controller => "widgets", :action => "index") ``` ## `be_routable` Passes if the path is recognized by Rails' routing. This is primarily intended to be used with `not_to` to specify routes that should not be routable. ```ruby expect(:get => "/widgets/1/edit").not_to be_routable ``` # `rake` tasks `rspec-rails` defines rake tasks to run the entire test suite (`rake spec`) and subsets of tests (e.g., `rake spec:models`). A full list of the available rake tasks can be seen by running `rake -T | grep rspec`. ## Customizing `rake` tasks If you want to customize the behavior of `rake spec`, you may [define your own task in the `Rakefile` for your project](https://www.relishapp.com/rspec/rspec-core/docs/command-line/rake-task). However, you must first clear the task that rspec-rails defined: ```ruby task("spec").clear ``` ### Webrat and Capybara You can choose between webrat or capybara for simulating a browser, automating a browser, or setting expectations using the matchers they supply. Just add your preference to the Gemfile: ```ruby gem "webrat" # ... or ... gem "capybara" ``` See [http://rubydoc.info/gems/rspec-rails/file/Capybara.md](http://rubydoc.info/gems/rspec-rails/file/Capybara.md) for more info on Capybara integration. # Contribute See [http://github.com/rspec/rspec-dev](http://github.com/rspec/rspec-dev). For `rspec-rails`-specific development information, see [DEV-README](https://github.com/rspec/rspec-rails/blob/master/DEV-README.md). # Also see * [http://github.com/rspec/rspec](http://github.com/rspec/rspec) * [http://github.com/rspec/rspec-core](http://github.com/rspec/rspec-core) * [http://github.com/rspec/rspec-expectations](http://github.com/rspec/rspec-expectations) * [http://github.com/rspec/rspec-mocks](http://github.com/rspec/rspec-mocks) ## Feature Requests & Bugs See rspec-rails-2.13.2/README_DEV.md000066400000000000000000000023641214604200000157720ustar00rootroot00000000000000# Information for rspec-rails developers rspec-rails lives in a complicated ecosystem. We need to run it against multiple versions of rails and multiple versions of Ruby as well. There are several tools already available to manage running against multiple versions of Ruby (e.g. rvm), and there are even some multi-rails tools (e.g. multi-rails) but we haven't found one that does exactly what we need here, so we've rolled our own. ## The short version gem install thor bundler thor version:use 3.1.3 rake ## The long version ### thor version:use The `thor version:use` task accepts any released version of rails, or either the 3-0-stable or master branches. thor version:use master thor version:use 3-0-stable thor version:use 3-1-stable thor version:use 3.1.3 # or any release >= 3.0.0 It then does a few things: * generates a .rails-version file with the version listed. This is used internally by assorted rake tasks. * installs the bundle * this includes binstubs, which are stored in ./bin At any time, if you want to change rails versions, run `thor version:use` with a new version number. To play it safe, you probably want to also run `rake clobber` to delete all the code generated by the previous rails version. rspec-rails-2.13.2/Rakefile000066400000000000000000000070661214604200000154660ustar00rootroot00000000000000require "bundler" begin Bundler.setup Bundler::GemHelper.install_tasks rescue raise "You need to install a bundle first. Try 'thor version:use 3.1.3'" end require 'yaml' require 'rspec' require 'rspec/core/rake_task' require 'cucumber/rake/task' desc "Run all examples" RSpec::Core::RakeTask.new(:spec) do |t| t.ruby_opts = %w[-w] t.rspec_opts = %w[--color] end Cucumber::Rake::Task.new(:cucumber) if RUBY_VERSION.to_f == 1.8 namespace :rcov do task :clean do rm_rf 'coverage.data' end desc "Run cucumber features using rcov" Cucumber::Rake::Task.new :cucumber do |t| t.cucumber_opts = %w{--format progress} t.rcov = true t.rcov_opts = %[-Ilib -Ispec --exclude "gems/*,features"] t.rcov_opts << %[--text-report --sort coverage --aggregate coverage.data] end desc "Run all examples using rcov" RSpec::Core::RakeTask.new :spec do |t| t.rcov = true t.rcov_opts = %[-Ilib -Ispec --exclude "gems/*,features"] t.rcov_opts << %[--text-report --sort coverage --no-html --aggregate coverage.data] end end task :rcov => ["rcov:clean", "rcov:spec", "rcov:cucumber"] end namespace :generate do desc "generate a fresh app with rspec installed" task :app do |t| unless File.directory?('./tmp/example_app') bindir = File.expand_path("bin") # Rails 4 cannot use a `rails` binstub generated by Bundler sh "rm -f #{bindir}/rails" sh "bundle exec rails new ./tmp/example_app --skip-javascript --skip-sprockets --skip-gemfile --skip-git --skip-test-unit" if test ?d, bindir Dir.chdir("./tmp/example_app") do Dir.mkdir("bin") unless File.directory?("bin") sh "ln -sf #{bindir}/rake bin/rake" sh "ln -sf #{bindir}/rspec bin/rspec" sh "ln -sf #{bindir}/cucumber bin/cucumber" application_file = File.read("config/application.rb") sh "rm config/application.rb" File.open("config/application.rb","w") do |f| f.write application_file.gsub("config.assets.enabled = true","config.assets.enabled = false") end end end end end desc "generate a bunch of stuff with generators" task :stuff do in_example_app "bin/rake rails:template LOCATION='../../templates/generate_stuff.rb'" end end def in_example_app(command) Dir.chdir("./tmp/example_app/") do Bundler.with_clean_env do sh command end end end namespace :db do task :migrate do in_example_app "bin/rake db:migrate" end namespace :test do task :prepare do in_example_app "bin/rake db:test:prepare" end end end desc "run a variety of specs against the generated app" task :smoke do in_example_app "LOCATION='../../templates/run_specs.rb' bin/rake rails:template --backtrace" end desc 'clobber generated files' task :clobber do rm_rf "pkg" rm_rf "tmp" rm_rf "doc" rm_rf ".yardoc" end namespace :clobber do desc "clobber the generated app" task :app do rm_rf "tmp/example_app" end end desc "Push docs/cukes to relishapp using the relish-client-gem" task :relish, :version do |t, args| raise "rake relish[VERSION]" unless args[:version] sh "cp Changelog.md features/" if `relish versions rspec/rspec-rails`.split.map(&:strip).include? args[:version] puts "Version #{args[:version]} already exists" else sh "relish versions:add rspec/rspec-rails:#{args[:version]}" end sh "relish push rspec/rspec-rails:#{args[:version]}" sh "rm features/Changelog.md" end task :default => [:spec, "clobber:app", "generate:app", "generate:stuff", :smoke, :cucumber] rspec-rails-2.13.2/Thorfile000066400000000000000000000005501214604200000155070ustar00rootroot00000000000000class Version < Thor desc "use VERSION", "installs the bundle the rails-VERSION" def use(version) `rm Gemfile.lock` `echo #{version} > ./.rails-version` "bundle install --binstubs".tap do |m| say m system m end end desc "which", "print out the configured rails version" def which say `cat ./.rails-version` end end rspec-rails-2.13.2/Upgrade.md000066400000000000000000000000301214604200000157120ustar00rootroot00000000000000See features/Upgrade.md rspec-rails-2.13.2/cucumber.yml000066400000000000000000000002361214604200000163410ustar00rootroot00000000000000default: --require features --format progress --tags ~@wip pretty: --require features --format pretty --tags ~@wip wip: --require features --tags @wip rspec-rails-2.13.2/features/000077500000000000000000000000001214604200000156265ustar00rootroot00000000000000rspec-rails-2.13.2/features/.nav000066400000000000000000000017071214604200000164200ustar00rootroot00000000000000- GettingStarted.md (Start from scratch) - Generators.md (Generators) - Transactions.md - Autotest.md - Changelog.md - Upgrade.md - RailsVersions.md (Rails versions) - model_specs: - errors_on.feature - mocks: - mock_model.feature - stub_model.feature - controller_specs: - Cookies.md - controller_spec.feature - isolation_from_views.feature - render_views.feature - anonymous_controller.feature - bypass_rescue.feature - engine_routes.feature - matchers: - new_record_matcher.feature - render_template_matcher.feature - redirect_to_matcher.feature - request_specs: - request_spec.feature - feature_specs: - feature_spec.feature - view_specs: - view_spec.feature - stub_template.feature - inferred_controller_path.feature - helper_specs: - helper_spec.feature - mailer_specs: - url_helpers.feature - routing_specs: - route_to_matcher.feature - be_routable_matcher.feature - named_routes.feature - engine_routes.feature rspec-rails-2.13.2/features/Autotest.md000066400000000000000000000014201214604200000177550ustar00rootroot00000000000000The `rspec:install` generator creates a `.rspec` file, which tells RSpec to tell Autotest that you're using RSpec. You'll also need to add the ZenTest and autotest-rails gems to your Gemfile: gem "ZenTest", "~> 4.4.2" gem "autotest-rails", "~> 4.1.0" If all of the gems in your Gemfile are installed in system gems, you can just type autotest If Bundler is managing any gems for you directly (i.e. you've got `:git` or `:path` attributes in the Gemfile), however, you may need to run bundle exec autotest If you do, you require Autotest's bundler plugin in a `.autotest` file in the project root directory or your home directory: require "autotest/bundler" Now you can just type `autotest`, it should prefix the generated shell command with `bundle exec`. rspec-rails-2.13.2/features/Generators.md000066400000000000000000000010301214604200000202530ustar00rootroot00000000000000If you type script/rails generate, the only RSpec generator you'll actually see is rspec:install. That's because RSpec is registered with Rails as the test framework, so whenever you generate application components like models, controllers, etc, RSpec specs are generated instead of Test::Unit tests. Note that the generators are there to help you get started, but they are no substitute for writing your own examples, and they are only guaranteed to work out of the box for with Rails' defaults (ActiveRecord, no Capybara or Webrat). rspec-rails-2.13.2/features/GettingStarted.md000066400000000000000000000044311214604200000211020ustar00rootroot00000000000000Install Rails-3 $ gem install rails -v "~> 3.0.0" ### Generate an app $ rails new example $ cd example ### Add rspec-rails to the Gemfile $ echo 'gem "rspec-rails", :group => [:development, :test]' >> Gemfile ### Install the bundle $ bundle install ### Bootstrap RSpec $ rails generate rspec:install ### Generate a scaffold $ rails generate scaffold Widgets name:string This generates files in the `app` and `spec` directories. The files in the `app` directory are generated by Rails, and Rails delegates the generation of the files in the `spec` directory to RSpec. ### Run migrations $ rake db:migrate && rake db:test:prepare ### Run RSpec $ rake spec or $ rspec spec --format documentation If all went well, you should see output ending with: 29 examples, 0 failures, 2 pending This output also includes the following controller spec: WidgetsController GET index assigns all widgets as @widgets GET show assigns the requested widget as @widget GET new assigns a new widget as @widget GET edit assigns the requested widget as @widget POST create with valid params creates a new Widget assigns a newly created widget as @widget redirects to the created widget with invalid params assigns a newly created but unsaved widget as @widget re-renders the 'new' template PUT update with valid params updates the requested widget assigns the requested widget as @widget redirects to the widget with invalid params assigns the widget as @widget re-renders the 'edit' template DELETE destroy destroys the requested widget redirects to the widgets list Output like this can help to quickly gain a high level understanding of how an object behaves. It also exposes which cases have been specified and which have not. Note the balance between the examples for the `create` and `update` actions. If the `redirects to the widget` example was missing from one or the other, it would be easy to spot. Take a look at the generated `spec/controllers/widgets_controller_spec.rb` to get a sense of how to organize your specs to generate output like this. rspec-rails-2.13.2/features/README.md000066400000000000000000000030321214604200000171030ustar00rootroot00000000000000rspec-rails extends Rails' built-in testing framework to support rspec examples for requests, controllers, models, views, helpers, mailers and routing. ## Rails-3 rspec-rails-2 supports rails-3.0.0 and later. For earlier versions of Rails, you need [rspec-rails-1.3](http://rspec.info). ## Install gem install rspec-rails This installs the following gems: rspec rspec-core rspec-expectations rspec-mocks rspec-rails ## Configure Add rspec-rails to the :test and :development groups in the Gemfile: group :test, :development do gem "rspec-rails", "~> 2.4" end It needs to be in the :development group to expose generators and rake tasks without having to type RAILS_ENV=test. Now you can run: script/rails generate rspec:install This adds the spec directory and some skeleton files, including a .rspec file. ## Webrat and Capybara You can choose between webrat or capybara for simulating a browser, automating a browser, or setting expectations using the matchers they supply. Just add your preference to the Gemfile: gem "webrat" gem "capybara" ## Issues The documentation for rspec-rails is a work in progress. We'll be adding Cucumber features over time, and clarifying existing ones. If you have specific features you'd like to see added, find the existing documentation incomplete or confusing, or, better yet, wish to write a missing Cucumber feature yourself, please [submit an issue](http://github.com/rspec/rspec-rails/issues) or a [pull request](http://github.com/rspec/rspec-rails). rspec-rails-2.13.2/features/RailsVersions.md000066400000000000000000000001701214604200000207510ustar00rootroot00000000000000 rails version | rspec-rails version 2.3 | 1.3.4 3.0 | >= 2.0 3.1 | >= 2.6 rspec-rails-2.13.2/features/Transactions.md000066400000000000000000000053621214604200000206260ustar00rootroot00000000000000When you run `rails generate rspec:install`, the `spec/spec_helper.rb` file includes the following configuration: RSpec.configure do |config| config.use_transactional_fixtures = true end The name of this setting is a bit misleading. What it really means in Rails is "run every test method within a transaction." In the context of rspec-rails, it means "run every example within a transaction." The idea is to start each example with a clean database, create whatever data is necessary for that example, and then remove that data by simply rolling back the transaction at the end of the example. ### Disabling transactions If you prefer to manage the data yourself, or using another tool like [database_cleaner](https://github.com/bmabey/database_cleaner) to do it for you, simply tell RSpec to tell Rails not to manage transactions: RSpec.configure do |config| config.use_transactional_fixtures = false end ### Data created in `before(:each)` are rolled back Any data you create in a `before(:each)` hook will be rolled back at the end of the example. This is a good thing because it means that each example is isolated from state that would otherwise be left around by the examples that already ran. For example: describe Widget do before(:each) do @widget = Widget.create end it "does something" do expect(@widget).to do_something end it "does something else" do expect(@widget).to do_something_else end end The `@widget` is recreated in each of the two examples above, so each example has a different object, _and_ the underlying data is rolled back so the data backing the `@widget` in each example is new. ### Data created in `before(:all)` are _not_ rolled back `before(:all)` hooks are invoked before the transaction is opened. You can use this to speed things up by creating data once before any example in a group is run, however, this introduces a number of complications and you should only do this if you have a firm grasp of the implications. Here are a couple of guidelines: 1. Be sure to clean up any data in an `after(:all)` hook: before(:all) do @widget = Widget.create! end after(:all) do @widget.destroy end If you don't do that, you'll leave data lying around that will eventually interfere with other examples. 2. Reload the object in a `before(:each)` hook. before(:all) do @widget = Widget.create! end before(:each) do @widget.reload end Even though database updates in each example will be rolled back, the object won't _know_ about those rollbacks so the object and its backing data can easily get out of sync. rspec-rails-2.13.2/features/Upgrade.md000066400000000000000000000074561214604200000175530ustar00rootroot00000000000000# Upgrading from rspec-rails-1.x to rspec-rails-2. This is a work in progress. Please submit errata, missing steps, or patches to the [rspec-rails issue tracker](https://github.com/rspec/rspec-rails/issues). ## Rake tasks Delete lib/tasks/rspec.rake, if present. Rake tasks now live in the rspec-rails gem. ## `spec_helper.rb` There were a few changes to the generated `spec/spec_helper.rb` file. We recommend the following: 1. set aside a copy of your existing `spec/spec_helper.rb` file. 2. run `rails generate rspec:install` 3. copy any customizations from your old spec_helper to the new one If you prefer to make the changes manually in the existing spec_helper, here is what you need to change: # rspec-1 require 'spec/autorun' Spec::Runner.configure do |config| ... end # rspec-2 require 'rspec/rails' RSpec.configure do |config| ... end ## Controller specs ### isolation from view templates By default, controller specs do _not_ render view templates. This keeps controller specs isolated from the content of views and their requirements. NOTE that the template must exist, but it will not be rendered. This is different from rspec-rails-1.x, in which the template didn't need to exist, but ActionController makes a number of new decisions in Rails 3 based on the existence of the template. To keep the RSpec code free of monkey patches, and to keep the rspec user experience simpler, we decided that this would be a fair trade-off. ### `response.should render_template` This needs to move from before the action to after. For example: # rspec-rails-1 controller.should render_template("edit") get :edit, :id => "37" # rspec-rails-2 get :edit, :id => "37" response.should render_template("edit") # rspec-rails-2 with expect syntax get :edit, :id => "37" expect(response).to render_template("edit") rspec-1 had to monkey patch Rails to get render_template to work before the action, and this broke a couple of times with Rails releases (requiring urgent fix releases in RSpec). Part of the philosophy of rspec-rails-2 is to rely on public APIs in Rails as much as possible. In this case, `render_template` delegates directly to Rails' `assert_template`, which only works after the action. ## View specs ### `view.should render_template` Rails changed the way it renders partials, so to set an expectation that a partial gets rendered, you need render view.should render_template(:partial => "widget/_row") ### stub_template Introduced in rspec-rails-2.2, simulates the presence of view templates on the file system. This supports isolation from partials rendered by the vew template that is the subject of a view example: stub_template "widgets/_widget.html.erb" => "This Content" ### No more `have_tag` or `have_text` Before Webrat came along, rspec-rails had its own `have_tag` and `have_text` matchers that wrapped Rails' `assert_select`. Webrat included replacements for these methods, as well as new matchers (`have_selector` and `have_xpath`), all of which rely on Nokogiri to do its work, and are far less brittle than RSpec's `have_tag`. Capybara has similar matchers, which will soon be available view specs (they are already available in controller specs with `render_views`). Given the brittleness of RSpec's `have_tag` and `have_text` matchers and the presence of new Webrat and Capybara matchers that do a better job, `have_tag` and `have_text` were not included in rspec-rails-2. ## Mocks, stubs, doubles ### as_new_record Earlier versions of the view generators generated stub_model with `:new_record? => true`. That is no longer recognized in rspec-rails-2, so you need to change this: stub_model(Widget, :new_record? => true) to this: stub_model(Widget).as_new_record Generators in 2.0.0 final release will do the latter. rspec-rails-2.13.2/features/controller_specs/000077500000000000000000000000001214604200000212065ustar00rootroot00000000000000rspec-rails-2.13.2/features/controller_specs/Cookies.md000066400000000000000000000035231214604200000231270ustar00rootroot00000000000000Controller specs wrap Rails controller tests, which expose a few different ways to access cookies: @request.cookies['key'] @response.cookies['key'] cookies['key'] rails-3.0.x and 3.1 handle these slightly differently, so to avoid confusion, we recommend the following guidelines: ### Recommended guidelines for rails-3.0.0 to 3.1.0 * Access cookies through the `request` and `response` objects in the spec. * Use `request.cookies` before the action to set up state. * Use `response.cookies` after the action to specify outcomes. * Use the `cookies` object in the controller action. * Use String keys.
# spec
request.cookies['foo'] = 'bar'
get :some_action
expect(response.cookies['foo']).to eq('modified bar')

# controller
def some_action
  cookies['foo'] = "modified #{cookies['foo']}"
end
#### Why use Strings instead of Symbols? The `cookies` objects in the spec come from Rack, and do not support indifferent access (i.e. `:foo` and `"foo"` are different keys). The `cookies` object in the controller _does_ support indifferent access, which is a bit confusing. This changed in rails-3.1, so you _can_ use symbol keys, but we recommend sticking with string keys for consistency. #### Why not use the `cookies` method? The `cookies` method combines the `request` and `response` cookies. This can lead to confusion when setting cookies in the example in order to set up state for the controller action. # does not work in rails 3.0.0 > 3.1.0 cookies['foo'] = 'bar' # this is not visible in the controller get :some_action ### Future versions of Rails There is code in the master branch in rails that makes cookie access more consistent so you can use the same `cookies` object before and after the action, and you can use String or Symbol keys. We'll update these docs accordingly when that is released. rspec-rails-2.13.2/features/controller_specs/README.md000066400000000000000000000030011214604200000224570ustar00rootroot00000000000000Controller specs live in `spec/controllers` or any example group with `:type => :controller`. A controller spec is an RSpec wrapper for a Rails functional test ([ActionController::TestCase::Behavior](https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/test_case.rb)). It allows you to simulate a single http request in each example, and then specify expected outcomes such as: * rendered templates * redirects * instance variables assigned in the controller to be shared with the view * cookies sent back with the response To specify outcomes, you can use: * standard rspec matchers (`expect(response.status).to eq(200)`) * standard test/unit assertions (`assert_equal 200, response.status`) * rails assertions (`assert_response 200`) * rails-specific matchers: * `expect(response).to render_template(wraps assert_template)` * `expect(response).to redirect_to(wraps assert_redirected_to)` * `expect(assigns(:widget)).to be_a_new(Widget)` ## Examples describe TeamsController do describe "GET index" do it "assigns @teams" do team = Team.create get :index expect(assigns(:teams)).to eq([team]) end it "renders the index template" do get :index expect(response).to render_template("index") end end end ## Views * by default, views are not rendered. See [views are stubbed by default](controller-specs/views-are-stubbed-by-default) and [render_views](controller-specs/render-views) for details. rspec-rails-2.13.2/features/controller_specs/anonymous_controller.feature000066400000000000000000000235711214604200000270660ustar00rootroot00000000000000Feature: anonymous controller Use the `controller` method to define an anonymous controller derived from `ApplicationController`. This is useful for specifying behavior like global error handling. To specify a different base class, you can pass the class explicitly to the controller method: controller(BaseController) You can also configure RSpec to use the described class: RSpec.configure do |c| c.infer_base_class_for_anonymous_controllers = true end describe BaseController do controller { ... } # ^^ creates an anonymous subclass of `BaseController` Scenario: specify error handling in ApplicationController Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "spec_helper" class ApplicationController < ActionController::Base class AccessDenied < StandardError; end rescue_from AccessDenied, :with => :access_denied private def access_denied redirect_to "/401.html" end end describe ApplicationController do controller do def index raise ApplicationController::AccessDenied end end describe "handling AccessDenied exceptions" do it "redirects to the /401.html page" do get :index expect(response).to redirect_to("/401.html") end end end """ When I run `rspec spec` Then the examples should all pass Scenario: specify error handling in subclass of ApplicationController Given a file named "spec/controllers/application_controller_subclass_spec.rb" with: """ruby require "spec_helper" class ApplicationController < ActionController::Base class AccessDenied < StandardError; end end class ApplicationControllerSubclass < ApplicationController rescue_from ApplicationController::AccessDenied, :with => :access_denied private def access_denied redirect_to "/401.html" end end describe ApplicationControllerSubclass do controller(ApplicationControllerSubclass) do def index raise ApplicationController::AccessDenied end end describe "handling AccessDenied exceptions" do it "redirects to the /401.html page" do get :index expect(response).to redirect_to("/401.html") end end end """ When I run `rspec spec` Then the examples should all pass Scenario: infer base class from the described class Given a file named "spec/controllers/base_class_can_be_inferred_spec.rb" with: """ruby require "spec_helper" RSpec.configure do |c| c.infer_base_class_for_anonymous_controllers = true end class ApplicationController < ActionController::Base; end class ApplicationControllerSubclass < ApplicationController; end describe ApplicationControllerSubclass do controller do def index render :text => "Hello World" end end it "creates an anonymous controller derived from ApplicationControllerSubclass" do expect(controller).to be_a_kind_of(ApplicationControllerSubclass) end end """ When I run `rspec spec` Then the examples should all pass Scenario: invoke around filter in base class Given a file named "spec/controllers/application_controller_around_filter_spec.rb" with: """ruby require "spec_helper" class ApplicationController < ActionController::Base around_filter :an_around_filter def an_around_filter @callback_invoked = true yield end end describe ApplicationController do controller do def index render :nothing => true end end it "invokes the callback" do get :index expect(assigns[:callback_invoked]).to be_true end end """ When I run `rspec spec` Then the examples should all pass Scenario: anonymous controllers only create resource routes Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "spec_helper" describe ApplicationController do controller do def index render :text => "index called" end def create render :text => "create called" end def new render :text => "new called" end def show render :text => "show called" end def edit render :text => "edit called" end def update render :text => "update called" end def destroy render :text => "destroy called" end def willerror render :text => "will not render" end end describe "#index" do it "responds to GET" do get :index expect(response.body).to eq "index called" end it "also responds to POST" do post :index expect(response.body).to eq "index called" end it "also responds to PUT" do put :index expect(response.body).to eq "index called" end it "also responds to DELETE" do delete :index expect(response.body).to eq "index called" end end describe "#create" do it "responds to POST" do post :create expect(response.body).to eq "create called" end # And the rest... %w{get post put delete}.each do |calltype| it "responds to #{calltype}" do send(calltype, :create) expect(response.body).to eq "create called" end end end describe "#new" do it "responds to GET" do get :new expect(response.body).to eq "new called" end # And the rest... %w{get post put delete}.each do |calltype| it "responds to #{calltype}" do send(calltype, :new) expect(response.body).to eq "new called" end end end describe "#edit" do it "responds to GET" do get :edit, :id => "anyid" expect(response.body).to eq "edit called" end it "requires the :id parameter" do expect { get :edit }.to raise_error(ActionController::RoutingError) end # And the rest... %w{get post put delete}.each do |calltype| it "responds to #{calltype}" do send(calltype, :edit, {:id => "anyid"}) expect(response.body).to eq "edit called" end end end describe "#show" do it "responds to GET" do get :show, :id => "anyid" expect(response.body).to eq "show called" end it "requires the :id parameter" do expect { get :show }.to raise_error(ActionController::RoutingError) end # And the rest... %w{get post put delete}.each do |calltype| it "responds to #{calltype}" do send(calltype, :show, {:id => "anyid"}) expect(response.body).to eq "show called" end end end describe "#update" do it "responds to PUT" do put :update, :id => "anyid" expect(response.body).to eq "update called" end it "requires the :id parameter" do expect { put :update }.to raise_error(ActionController::RoutingError) end # And the rest... %w{get post put delete}.each do |calltype| it "responds to #{calltype}" do send(calltype, :update, {:id => "anyid"}) expect(response.body).to eq "update called" end end end describe "#destroy" do it "responds to DELETE" do delete :destroy, :id => "anyid" expect(response.body).to eq "destroy called" end it "requires the :id parameter" do expect { delete :destroy }.to raise_error(ActionController::RoutingError) end # And the rest... %w{get post put delete}.each do |calltype| it "responds to #{calltype}" do send(calltype, :destroy, {:id => "anyid"}) expect(response.body).to eq "destroy called" end end end describe "#willerror" do it "cannot be called" do expect { get :willerror }.to raise_error(ActionController::RoutingError) end end end """ When I run `rspec spec` Then the examples should all pass Scenario: draw custom routes for anonymous controllers Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "spec_helper" describe ApplicationController do controller do def custom render :text => "custom called" end end specify "a custom action can be requested if routes are drawn manually" do routes.draw { get "custom" => "anonymous#custom" } get :custom expect(response.body).to eq "custom called" end end """ When I run `rspec spec` Then the examples should all pass Scenario: refer to application routes in the controller under test Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "spec_helper" Rails.application.routes.draw do match "/login" => "sessions#new", :as => "login", :via => "get" end describe ApplicationController do controller do def index redirect_to login_url end end it "redirects to the login page" do get :index expect(response).to redirect_to("/login") end end """ When I run `rspec spec` Then the examples should all pass rspec-rails-2.13.2/features/controller_specs/bypass_rescue.feature000066400000000000000000000040301214604200000254270ustar00rootroot00000000000000Feature: bypass rescue Use `bypass_rescue` to bypass both Rails' default handling of errors in controller actions, and any custom handling declared with a `rescue_from` statement. This lets you specify details of the exception being raised, regardless of how it might be handled upstream. Background: Given a file named "spec/controllers/gadgets_controller_spec_context.rb" with: """ruby class AccessDenied < StandardError; end class ApplicationController < ActionController::Base rescue_from AccessDenied, :with => :access_denied private def access_denied redirect_to "/401.html" end end """ Scenario: standard exception handling using `rescue_from` Given a file named "spec/controllers/gadgets_controller_spec.rb" with: """ruby require "spec_helper" require 'controllers/gadgets_controller_spec_context' describe GadgetsController do before do def controller.index raise AccessDenied end end describe "index" do it "redirects to the /401.html page" do get :index expect(response).to redirect_to("/401.html") end end end """ When I run `rspec spec/controllers/gadgets_controller_spec.rb` Then the examples should all pass Scenario: bypass `rescue_from` handling with `bypass_rescue` Given a file named "spec/controllers/gadgets_controller_spec.rb" with: """ruby require "spec_helper" require 'controllers/gadgets_controller_spec_context' describe GadgetsController do before do def controller.index raise AccessDenied end end describe "index" do it "raises AccessDenied" do bypass_rescue expect { get :index }.to raise_error(AccessDenied) end end end """ When I run `rspec spec/controllers/gadgets_controller_spec.rb` Then the examples should all pass rspec-rails-2.13.2/features/controller_specs/controller_spec.feature000066400000000000000000000027121214604200000257620ustar00rootroot00000000000000Feature: controller spec Scenario: simple passing example Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "spec_helper" describe WidgetsController do describe "GET index" do it "has a 200 status code" do get :index expect(response.status).to eq(200) end end end """ When I run `rspec spec` Then the example should pass Scenario: controller is exposed to global before hooks Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "spec_helper" RSpec.configure {|c| c.before { expect(controller).not_to be_nil }} describe WidgetsController do describe "GET index" do it "doesn't matter" do end end end """ When I run `rspec spec` Then the example should pass Scenario: controller is extended with a helper module Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "spec_helper" module MyHelper def my_variable end end RSpec.configure {|c| c.include MyHelper } describe WidgetsController do let(:my_variable) { 'is a value' } describe 'something' do specify { expect(my_variable).to eq 'is a value' } end end """ When I run `rspec spec` Then the example should pass rspec-rails-2.13.2/features/controller_specs/engine_routes.feature000066400000000000000000000025761214604200000254430ustar00rootroot00000000000000Feature: engine routes for controllers Controller specs can specify the routeset that will be used for the example group. This is most useful when testing Rails engines. @unsupported-on-rails-3-0 Scenario: specify engine route Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "spec_helper" # A very simple Rails engine module MyEngine class Engine < ::Rails::Engine isolate_namespace MyEngine end Engine.routes.draw do resources :widgets, :only => [:show] do get :random, :on => :collection end end class WidgetsController < ::ActionController::Base def random @random_widget = Widget.all.shuffle.first redirect_to widget_path(@random_widget) end def show @widget = Widget.find(params[:id]) render :text => @widget.name end end end describe MyEngine::WidgetsController do routes { MyEngine::Engine.routes } it "redirects to a random widget" do widget1 = Widget.create!(:name => "Widget 1") widget2 = Widget.create!(:name => "Widget 2") get :random expect(response).to be_redirect expect(response).to redirect_to(assigns(:random_widget)) end end """ When I run `rspec spec` Then the examples should all pass rspec-rails-2.13.2/features/controller_specs/isolation_from_views.feature000066400000000000000000000056161214604200000270340ustar00rootroot00000000000000Feature: views are stubbed by default By default, controller specs stub views with a template that renders an empty string instead of the views in the app. This allows you specify which view template an action should try to render regardless of whether the template compiles cleanly. NOTE: unlike rspec-rails-1.x, the real template must exist. Scenario: expect template that is rendered by controller action (passes) Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "spec_helper" describe WidgetsController do describe "index" do it "renders the index template" do get :index expect(response).to render_template("index") expect(response.body).to eq "" end it "renders the widgets/index template" do get :index expect(response).to render_template("widgets/index") expect(response.body).to eq "" end end end """ When I run `rspec spec` Then the examples should all pass Scenario: expect template that is not rendered by controller action (fails) Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "spec_helper" describe WidgetsController do describe "index" do it "renders the 'new' template" do get :index expect(response).to render_template("new") end end end """ When I run `rspec spec` Then the output should contain "1 example, 1 failure" Scenario: expect empty templates to render when view path is changed at runtime (passes) Given a file named "spec/controllers/things_controller_spec.rb" with: """ruby require "spec_helper" describe ThingsController do describe "custom_action" do it "renders an empty custom_action template" do controller.prepend_view_path 'app/views' controller.append_view_path 'app/views' get :custom_action expect(response).to render_template("custom_action") expect(response.body).to eq "" end end end """ When I run `rspec spec` Then the examples should all pass Scenario: expect template to render the real template with render_views when view path is changed at runtime Given a file named "spec/controllers/things_controller_spec.rb" with: """ruby require "spec_helper" describe ThingsController do render_views it "renders the real custom_action template" do controller.prepend_view_path 'app/views' get :custom_action expect(response).to render_template("custom_action") expect(response.body).to match(/template for a custom action/) end end """ When I run `rspec spec` Then the examples should all pass rspec-rails-2.13.2/features/controller_specs/render_views.feature000066400000000000000000000062221214604200000252610ustar00rootroot00000000000000Feature: render_views You can tell a controller example group to render views with the `render_views` declaration in any individual group, or globally. Scenario: render_views directly in a single group Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "spec_helper" describe WidgetsController do render_views describe "GET index" do it "says 'Listing widgets'" do get :index expect(response.body).to match /Listing widgets/m end end end """ When I run `rspec spec` Then the examples should all pass Scenario: render_views on and off in nested groups Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "spec_helper" describe WidgetsController do context "with render_views" do render_views describe "GET index" do it "renders the actual template" do get :index expect(response.body).to match /Listing widgets/m end end context "with render_views(false) nested in a group with render_views" do render_views false describe "GET index" do it "renders the RSpec generated template" do get :index expect(response.body).to eq("") end end end end context "without render_views" do describe "GET index" do it "renders the RSpec generated template" do get :index expect(response.body).to eq("") end end end context "with render_views again" do render_views describe "GET index" do it "renders the actual template" do get :index expect(response.body).to match /Listing widgets/m end end end end """ When I run `rspec spec --order default --format documentation` Then the output should contain: """ruby WidgetsController with render_views GET index renders the actual template with render_views(false) nested in a group with render_views GET index renders the RSpec generated template without render_views GET index renders the RSpec generated template with render_views again GET index renders the actual template """ Scenario: render_views globally Given a file named "spec/support/render_views.rb" with: """ruby RSpec.configure do |config| config.render_views end """ And a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "spec_helper" describe WidgetsController do describe "GET index" do it "renders the index template" do get :index expect(response.body).to match /Listing widgets/m end end end """ When I run `rspec spec` Then the examples should all pass rspec-rails-2.13.2/features/feature_specs/000077500000000000000000000000001214604200000204565ustar00rootroot00000000000000rspec-rails-2.13.2/features/feature_specs/feature_spec.feature000066400000000000000000000025531214604200000245050ustar00rootroot00000000000000Feature: feature spec Feature specs are high-level tests meant to exercise slices of functionality through an application. They should drive the application only via its external interface, usually web pages. Feature specs require the [capybara](http://github.com/jnicklas/capybara) gem, version 2.0.0 or later. Refer to the [capybara API documentation](http://rubydoc.info/github/jnicklas/capybara/master) for more information on the methods and matchers that can be used in feature specs. The `feature` and `scenario` DSL correspond to `describe` and `it`, respectively. These methods are simply aliases that allow feature specs to read more as [customer tests](http://c2.com/cgi/wiki?CustomerTest) and [acceptance tests](http://c2.com/cgi/wiki?AcceptanceTest). Scenario: specify creating a Widget by driving the application with capybara Given a file named "spec/features/widget_management_spec.rb" with: """ruby require "spec_helper" feature "Widget management" do scenario "User creates a new widget" do visit "/widgets/new" fill_in "Name", :with => "My Widget" click_button "Create Widget" expect(page).to have_text("Widget was successfully created.") end end """ When I run `rspec spec/features/widget_management_spec.rb` Then the example should pass rspec-rails-2.13.2/features/helper_specs/000077500000000000000000000000001214604200000203025ustar00rootroot00000000000000rspec-rails-2.13.2/features/helper_specs/helper_spec.feature000066400000000000000000000071031214604200000241510ustar00rootroot00000000000000Feature: helper spec Helper specs live in `spec/helpers`, or any example group with `:type => :helper`. Helper specs expose a `helper` object, which includes the helper module being specified, the `ApplicationHelper` module (if there is one) and all of the helpers built into Rails. It does not include the other helper modules in your app. To access the helper methods you're specifying, simply call them directly on the `helper` object. NOTE: helper methods defined in controllers are not included. Scenario: helper method that returns a value Given a file named "spec/helpers/application_helper_spec.rb" with: """ruby require "spec_helper" describe ApplicationHelper do describe "#page_title" do it "returns the default title" do expect(helper.page_title).to eq("RSpec is your friend") end end end """ And a file named "app/helpers/application_helper.rb" with: """ruby module ApplicationHelper def page_title "RSpec is your friend" end end """ When I run `rspec spec/helpers/application_helper_spec.rb` Then the examples should all pass Scenario: helper method that accesses an instance variable Given a file named "spec/helpers/application_helper_spec.rb" with: """ruby require "spec_helper" describe ApplicationHelper do describe "#page_title" do it "returns the instance variable" do assign(:title, "My Title") expect(helper.page_title).to eql("My Title") end end end """ And a file named "app/helpers/application_helper.rb" with: """ruby module ApplicationHelper def page_title @title || nil end end """ When I run `rspec spec/helpers/application_helper_spec.rb` Then the examples should all pass Scenario: application helper is included in helper object Given a file named "spec/helpers/widgets_helper_spec.rb" with: """ruby require "spec_helper" describe WidgetsHelper do describe "#widget_title" do it "includes the app name" do assign(:title, "This Widget") expect(helper.widget_title).to eq("The App: This Widget") end end end """ And a file named "app/helpers/application_helper.rb" with: """ruby module ApplicationHelper def app_name "The App" end end """ And a file named "app/helpers/widgets_helper.rb" with: """ruby module WidgetsHelper def widget_title "#{app_name}: #{@title}" end end """ When I run `rspec spec/helpers/widgets_helper_spec.rb` Then the examples should all pass Scenario: url helpers are defined Given a file named "spec/helpers/widgets_helper_spec.rb" with: """ruby require "spec_helper" describe WidgetsHelper do describe "#link_to_widget" do it "links to a widget using its name" do widget = Widget.create!(:name => "This Widget") expect(helper.link_to_widget(widget)).to include("This Widget") expect(helper.link_to_widget(widget)).to include(widget_path(widget)) end end end """ And a file named "app/helpers/widgets_helper.rb" with: """ruby module WidgetsHelper def link_to_widget(widget) link_to(widget.name, widget_path(widget)) end end """ When I run `rspec spec/helpers/widgets_helper_spec.rb` Then the examples should all pass rspec-rails-2.13.2/features/mailer_specs/000077500000000000000000000000001214604200000202745ustar00rootroot00000000000000rspec-rails-2.13.2/features/mailer_specs/url_helpers.feature000066400000000000000000000022601214604200000241750ustar00rootroot00000000000000Feature: URL helpers in mailer examples Scenario: using URL helpers with default options Given a file named "config/initializers/mailer_defaults.rb" with: """ruby Rails.configuration.action_mailer.default_url_options = { :host => 'example.com' } """ And a file named "spec/mailers/notifications_spec.rb" with: """ruby require 'spec_helper' describe Notifications do it 'should have access to URL helpers' do expect { gadgets_url }.not_to raise_error end end """ When I run `rspec spec` Then the examples should all pass Scenario: using URL helpers without default options Given a file named "config/initializers/mailer_defaults.rb" with: """ruby # no default options """ And a file named "spec/mailers/notifications_spec.rb" with: """ruby require 'spec_helper' describe Notifications do it 'should have access to URL helpers' do expect { gadgets_url :host => 'example.com' }.not_to raise_error expect { gadgets_url }.to raise_error end end """ When I run `rspec spec` Then the examples should all pass rspec-rails-2.13.2/features/matchers/000077500000000000000000000000001214604200000174345ustar00rootroot00000000000000rspec-rails-2.13.2/features/matchers/README.md000066400000000000000000000007371214604200000207220ustar00rootroot00000000000000rspec-rails offers a number of custom matchers, most of which are rspec-compatible wrappers for Rails' assertions. ### redirects # delegates to assert_redirected_to expect(response).to redirect_to(path) ### templates # delegates to assert_template expect(response).to render_template(template_name) ### assigned objects # passes if assigns(:widget) is an instance of Widget # and it is not persisted expect(assigns(:widget)).to be_a_new(Widget) rspec-rails-2.13.2/features/matchers/new_record_matcher.feature000066400000000000000000000022061214604200000246430ustar00rootroot00000000000000Feature: be_a_new matcher The `be_a_new` matcher accepts a class and passes if the subject is an instance of that class that returns false to persisted? You can also chain `with` on `be_a_new` with a hash of attributes to specify the subject has equal attributes. Scenario: example spec with four be_a_new possibilities Given a file named "spec/models/widget_spec.rb" with: """ruby require "spec_helper" describe Widget do context "when initialized" do subject(:widget) { Widget.new } it "is a new widget" do expect(widget).to be_a_new(Widget) end it "is not a new string" do expect(widget).not_to be_a_new(String) end end context "when saved" do subject(:widget) { Widget.create } it "is not a new widget" do expect(widget).not_to be_a_new(Widget) end it "is not a new string" do expect(widget).not_to be_a_new(String) end end end """ When I run `rspec spec/models/widget_spec.rb` Then the examples should all pass rspec-rails-2.13.2/features/matchers/redirect_to_matcher.feature000066400000000000000000000026111214604200000250170ustar00rootroot00000000000000Feature: redirect_to matcher The `redirect_to` matcher is used to specify that a request redirects to a given template or action. It delegates to [`assert_redirected_to`](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_redirected_to). It is available in controller specs (spec/controllers) and request specs (spec/requests). Scenario: redirect_to with four possible options Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "spec_helper" describe WidgetsController do describe "#create" do subject { post :create, :widget => { :name => "Foo" } } it "redirects to widget_url(@widget)" do expect(subject).to redirect_to(widget_url(assigns(:widget))) end it "redirects_to :action => :show" do expect(subject).to redirect_to :action => :show, :id => assigns(:widget).id end it "redirects_to(@widget)" do expect(subject).to redirect_to(assigns(:widget)) end it "redirects_to /widgets/:id" do expect(subject).to redirect_to("/widgets/#{assigns(:widget).id}") end end end """ When I run `rspec spec/controllers/widgets_controller_spec.rb` Then the examples should all pass rspec-rails-2.13.2/features/matchers/relation_match_array.feature000066400000000000000000000013521214604200000252010ustar00rootroot00000000000000Feature: ActiveRecord::Relation match array The `match_array` matcher can be used with an `ActiveRecord::Relation` (scope). The assertion will pass if the scope would return all of the elements specified in the array on the right hand side. Scenario: example spec with relation match_array matcher Given a file named "spec/models/widget_spec.rb" with: """ruby require "spec_helper" describe Widget do let!(:widgets) { Array.new(3) { Widget.create } } subject { Widget.scoped } it "returns all widgets in any order" do expect(subject).to match_array(widgets) end end """ When I run `rspec spec/models/widget_spec.rb` Then the examples should all pass rspec-rails-2.13.2/features/matchers/render_template_matcher.feature000066400000000000000000000031521214604200000256670ustar00rootroot00000000000000Feature: render_template matcher The `render_template` matcher is used to specify that a request renders a given template. It delegates to [`assert_template`](http://api.rubyonrails.org/classes/ActionController/TemplateAssertions.html#method-i-assert_template) It is available in controller specs (spec/controllers) and request specs (spec/requests). NOTE: use `redirect_to(:action => 'new')` for redirects, not `render_template`. Scenario: render_template with three possible options Given a file named "spec/controllers/gadgets_spec.rb" with: """ruby require "spec_helper" describe GadgetsController do describe "GET #index" do subject { get :index } it "renders the index template" do expect(subject).to render_template(:index) expect(subject).to render_template("index") expect(subject).to render_template("gadgets/index") end end end """ When I run `rspec spec/controllers/gadgets_spec.rb` Then the examples should all pass Scenario: render_template in a view spec Given a file named "spec/views/gadgets/index.html.erb_spec.rb" with: """ruby require "spec_helper" describe "gadgets/index" do it "renders the index template" do assign(:gadgets, [stub_model(Gadget)]) render expect(view).to render_template(:index) expect(view).to render_template("index") expect(view).to render_template("gadgets/index") end end """ When I run `rspec spec/views` Then the examples should all pass rspec-rails-2.13.2/features/mocks/000077500000000000000000000000001214604200000167425ustar00rootroot00000000000000rspec-rails-2.13.2/features/mocks/mock_model.feature000066400000000000000000000107211214604200000224310ustar00rootroot00000000000000Feature: mock_model The `mock_model` method generates a test double that acts like an instance of `ActiveModel`. This is different from the `stub_model` method which generates an instance of a real model class. The benefit of `mock_model` over `stub_model` is that it is a true double, so the examples are not dependent on the behavior (or mis-behavior), or even the existence of any other code. If you're working on a controller spec and you need a model that doesn't exist, you can pass `mock_model` a string and the generated object will act as though its an instance of the class named by that string. Scenario: passing a string that represents a non-existent constant Given a file named "spec/models/car_spec.rb" with: """ruby require "spec_helper" describe "mock_model('Car') with no Car constant in existence" do it "generates a constant" do expect(Object.const_defined?(:Car)).to be_false mock_model("Car") expect(Object.const_defined?(:Car)).to be_true end describe "generates an object that ..." do it "returns the correct name" do car = mock_model("Car") expect(car.class.name).to eq("Car") end it "says it is a Car" do car = mock_model("Car") expect(car).to be_a(Car) end end end """ When I run `rspec spec/models/car_spec.rb` Then the examples should all pass Scenario: passing a string that represents an existing constant Given a file named "spec/models/widget_spec.rb" with: """ruby require "spec_helper" describe Widget do it "uses the existing constant" do widget = mock_model("Widget") expect(widget).to be_a(Widget) end end """ When I run `rspec spec/models/widget_spec.rb` Then the examples should all pass Scenario: passing a class that does not extend ActiveModel::Naming Given a file named "spec/models/string_spec.rb" with: """ruby require "spec_helper" describe String do it "raises" do expect { mock_model(String) }.to raise_exception end end """ When I run `rspec spec/models/string_spec.rb` Then the examples should all pass Scenario: passing an Active Record constant Given a file named "spec/models/widget_spec.rb" with: """ruby require "spec_helper" describe Widget do let(:widget) { mock_model(Widget) } it "is valid by default" do expect(widget).to be_valid end it "is not a new record by default" do expect(widget).not_to be_new_record end it "can be converted to a new record" do expect(widget.as_new_record).to be_new_record end it "sets :id to nil upon destroy" do widget.destroy expect(widget.id).to be_nil end end """ When I run `rspec spec/models/widget_spec.rb` Then the examples should all pass Scenario: passing an Active Record constant with method stubs Given a file named "spec/models/widget_spec.rb" with: """ruby require "spec_helper" describe "mock_model(Widget) with stubs" do let(:widget) do mock_model Widget, :foo => "bar", :save => true, :update_attributes => false end it "supports stubs for methods that don't exist in ActiveModel or ActiveRecord" do expect(widget.foo).to eq("bar") end it "supports stubs for methods that do exist" do expect(widget.save).to eq(true) expect(widget.update_attributes).to be_false end describe "#errors" do context "with update_attributes => false" do it "is not empty" do expect(widget.errors).not_to be_empty end end end end """ When I run `rspec spec/models/widget_spec.rb` Then the examples should all pass Scenario: mock_model outside rails Given a file named "mock_model_outside_rails_spec.rb" with: """ruby require 'rspec/rails/mocks' describe "Foo" do it "is mockable" do foo = mock_model("Foo") expect(foo.id).to eq(1001) expect(foo.to_param).to eq("1001") end end """ When I run `rspec mock_model_outside_rails_spec.rb` Then the examples should all pass rspec-rails-2.13.2/features/mocks/stub_model.feature000066400000000000000000000033141214604200000224550ustar00rootroot00000000000000Feature: stub_model The stub_model method generates an instance of a Active Model model. While you can use stub_model in any example (model, view, controller, helper), it is especially useful in view examples, which are inherently more state-based than interaction-based. Scenario: passing an Active Record constant with a hash of stubs Given a file named "spec/models/widget_spec.rb" with: """ruby require "spec_helper" describe "stub_model(Widget) with a hash of stubs" do let(:widget) do stub_model Widget, :id => 5, :random_attribute => true end it "stubs :id" do expect(widget.id).to eql(5) end it "stubs :random_attribute" do expect(widget.random_attribute).to be_true end it "returns false for new_record? if :id is set" do expect(widget).not_to be_new_record end it "can be converted to a new record" do widget.as_new_record expect(widget).to be_new_record end end """ When I run `rspec spec/models/widget_spec.rb` Then the examples should all pass Scenario: passing an Active Record constant with a block of stubs Given a file named "spec/models/widget_spec.rb" with: """ruby require "spec_helper" describe "stub_model(Widget) with a block of stubs" do let(:widget) do stub_model Widget do |widget| widget.id = 5 end end it "stubs :id" do expect(widget.id).to eql(5) end end """ When I run `rspec spec/models/widget_spec.rb` Then the examples should all pass rspec-rails-2.13.2/features/model_specs/000077500000000000000000000000001214604200000201235ustar00rootroot00000000000000rspec-rails-2.13.2/features/model_specs/README.md000066400000000000000000000012651214604200000214060ustar00rootroot00000000000000Model specs live in `spec/models` or any example group with `:type => :model`. A model spec is a thin wrapper for an ActiveSupport::TestCase, and includes all of the behavior and assertions that it provides, in addition to RSpec's own behavior and expectations. ## Examples require "spec_helper" describe Post do context "with 2 or more comments" do it "orders them in reverse chronologically" do post = Post.create! comment1 = post.comments.create!(:body => "first comment") comment2 = post.comments.create!(:body => "second comment") expect(post.reload.comments).to eq([comment2, comment1]) end end end rspec-rails-2.13.2/features/model_specs/errors_on.feature000066400000000000000000000035401214604200000235120ustar00rootroot00000000000000Feature: errors_on Scenario: with one validation error Given a file named "spec/models/widget_spec.rb" with: """ruby require "spec_helper" class ValidatingWidget < ActiveRecord::Base self.table_name = :widgets validates_presence_of :name # In Rails 4, mass assignment protection is implemented on controllers attr_accessible :name if ::Rails::VERSION::STRING < '4' validates_length_of :name, :minimum => 10, :on => :publication end describe ValidatingWidget do it "fails validation with no name (using error_on)" do expect(ValidatingWidget.new).to have(1).error_on(:name) end it "fails validation with no name (using errors_on)" do expect(ValidatingWidget.new).to have(1).errors_on(:name) end it "fails validation with no name expecting a specific message" do expect(ValidatingWidget.new.errors_on(:name)).to include("can't be blank") end it "fails validation with a short name (using a validation context)" do expect(ValidatingWidget.new(:name => "too short")). to have(1).errors_on(:name, :context => :publication) end it "passes validation with a longer name (using a validation context)" do expect(ValidatingWidget.new(:name => "a longer name")). to have(0).errors_on(:name, :context => :publication) end it "passes validation with a name (using 0)" do expect(ValidatingWidget.new(:name => "liquid nitrogen")).to have(0).errors_on(:name) end it "passes validation with a name (using :no)" do expect(ValidatingWidget.new(:name => "liquid nitrogen")).to have(:no).errors_on(:name) end end """ When I run `rspec spec/models/widget_spec.rb` Then the examples should all pass rspec-rails-2.13.2/features/model_specs/transactional_examples.feature000066400000000000000000000053141214604200000262430ustar00rootroot00000000000000Feature: transactional examples By default rspec executes each individual example in a transaction. You can also explicitly enable/disable transactions the configuration property 'use_transactional_examples'. Scenario: run in transactions (default) Given a file named "spec/models/widget_spec.rb" with: """ruby require "spec_helper" describe Widget do it "has none to begin with" do expect(Widget.count).to eq 0 end it "has one after adding one" do Widget.create expect(Widget.count).to eq 1 end it "has none after one was created in a previous example" do expect(Widget.count).to eq 0 end end """ When I run `rspec spec/models/widget_spec.rb` Then the examples should all pass Scenario: run in transactions (explicit) Given a file named "spec/models/widget_spec.rb" with: """ruby require "spec_helper" RSpec.configure do |c| c.use_transactional_examples = true end describe Widget do it "has none to begin with" do expect(Widget.count).to eq 0 end it "has one after adding one" do Widget.create expect(Widget.count).to eq 1 end it "has none after one was created in a previous example" do expect(Widget.count).to eq 0 end end """ When I run `rspec spec/models/widget_spec.rb` Then the examples should all pass Scenario: disable transactions (explicit) Given a file named "spec/models/widget_spec.rb" with: """ruby require "spec_helper" RSpec.configure do |c| c.use_transactional_examples = false c.order = "default" end describe Widget do it "has none to begin with" do expect(Widget.count).to eq 0 end it "has one after adding one" do Widget.create expect(Widget.count).to eq 1 end it "has one after one was created in a previous example" do expect(Widget.count).to eq 1 end after(:all) { Widget.destroy_all } end """ When I run `rspec spec/models/widget_spec.rb` Then the examples should all pass Scenario: run in transactions with fixture Given a file named "spec/models/thing_spec.rb" with: """ruby require "spec_helper" describe Thing do fixtures :things it "fixture method defined" do things(:one) end end """ Given a file named "spec/fixtures/things.yml" with: """ one: name: MyString """ When I run `rspec spec/models/thing_spec.rb` Then the examples should all pass rspec-rails-2.13.2/features/request_specs/000077500000000000000000000000001214604200000205135ustar00rootroot00000000000000rspec-rails-2.13.2/features/request_specs/request_spec.feature000066400000000000000000000032711214604200000245750ustar00rootroot00000000000000Feature: request spec Request specs provide a thin wrapper around Rails' integration tests, and are designed to drive behavior through the full stack, including routing (provided by Rails) and without stubbing (that's up to you). With request specs, you can: * specify a single request * specify multiple requests across multiple controllers * specify multiple requests across multiple sessions Check the rails documentation on integration tests for more information. RSpec provides two matchers that delegate to Rails assertions: render_template # delegates to assert_template redirect_to # delegates to assert_redirected_to Check the Rails docs for details on these methods as well. [Capybara](http://github.com/jnicklas/capybara) is no longer supported in request specs as of Capybara 2.0.0. The recommended way to use Capybara is with [feature specs](../feature-specs/feature-spec). Scenario: specify managing a Widget with Rails integration methods Given a file named "spec/requests/widget_management_spec.rb" with: """ruby require "spec_helper" describe "Widget management" do it "creates a Widget and redirects to the Widget's page" do get "/widgets/new" expect(response).to render_template(:new) post "/widgets", :widget => {:name => "My Widget"} expect(response).to redirect_to(assigns(:widget)) follow_redirect! expect(response).to render_template(:show) expect(response.body).to include("Widget was successfully created.") end end """ When I run `rspec spec/requests/widget_management_spec.rb` Then the example should pass rspec-rails-2.13.2/features/routing_specs/000077500000000000000000000000001214604200000205125ustar00rootroot00000000000000rspec-rails-2.13.2/features/routing_specs/README.md000066400000000000000000000011501214604200000217660ustar00rootroot00000000000000Routing specs live in the `spec/routing` directory, or any example group with `:type => :routing`. Simple apps with nothing but standard RESTful routes won't get much value from routing specs, but they can provide significant value when used to specify customized routes, like vanity links, slugs, etc. expect(:get => "/articles/2012/11/when-to-use-routing-specs").to route_to( :controller => "articles", :month => "2012-11", :slug => "when-to-use-routing-specs" ) They are also valuable for routes that should not be available: expect(:delete => "/accounts/37").not_to be_routable rspec-rails-2.13.2/features/routing_specs/be_routable_matcher.feature000066400000000000000000000047121214604200000260610ustar00rootroot00000000000000Feature: be_routable matcher The `be_routable` matcher is best used with `should_not` to specify that a given route should not be routable. It is available in routing specs (in spec/routing) and controller specs (in spec/controllers). Scenario: specify routeable route should not be routable (fails) Given a file named "spec/routing/widgets_routing_spec.rb" with: """ruby require "spec_helper" describe "routes for Widgets" do it "does not route to widgets" do expect(:get => "/widgets").not_to be_routable end end """ When I run `rspec spec/routing/widgets_routing_spec.rb` Then the output should contain "1 example, 1 failure" Scenario: specify non-routeable route should not be routable (passes) Given a file named "spec/routing/widgets_routing_spec.rb" with: """ruby require "spec_helper" describe "routes for Widgets" do it "does not route to widgets/foo/bar" do expect(:get => "/widgets/foo/bar").not_to be_routable end end """ When I run `rspec spec/routing/widgets_routing_spec.rb` Then the examples should all pass Scenario: specify routeable route should be routable (passes) Given a file named "spec/routing/widgets_routing_spec.rb" with: """ruby require "spec_helper" describe "routes for Widgets" do it "routes to /widgets" do expect(:get => "/widgets").to be_routable end end """ When I run `rspec spec/routing/widgets_routing_spec.rb` Then the examples should all pass Scenario: specify non-routeable route should be routable (fails) Given a file named "spec/routing/widgets_routing_spec.rb" with: """ruby require "spec_helper" describe "routes for Widgets" do it "routes to widgets/foo/bar" do expect(:get => "/widgets/foo/bar").to be_routable end end """ When I run `rspec spec/routing/widgets_routing_spec.rb` Then the output should contain "1 example, 1 failure" Scenario: be_routable in a controller spec Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "spec_helper" describe WidgetsController do it "routes to /widgets" do expect(:get => "/widgets").to be_routable end end """ When I run `rspec spec/controllers/widgets_controller_spec.rb` Then the examples should all pass rspec-rails-2.13.2/features/routing_specs/engine_routes.feature000066400000000000000000000017401214604200000247370ustar00rootroot00000000000000Feature: engine routes Routing specs can specify the routeset that will be used for the example group. This is most useful when testing Rails engines. @unsupported-on-rails-3-0 Scenario: specify engine route Given a file named "spec/routing/engine_routes_spec.rb" with: """ruby require "spec_helper" # A very simple Rails engine module MyEngine class Engine < ::Rails::Engine isolate_namespace MyEngine end Engine.routes.draw do resources :widgets, :only => [:index] end class WidgetsController < ::ActionController::Base def index end end end describe MyEngine::WidgetsController do routes { MyEngine::Engine.routes } it "routes to the list of all widgets" do expect(:get => widgets_path). to route_to(:controller => "my_engine/widgets", :action => "index") end end """ When I run `rspec spec` Then the examples should all pass rspec-rails-2.13.2/features/routing_specs/named_routes.feature000066400000000000000000000007741214604200000245640ustar00rootroot00000000000000Feature: named routes Routing specs have access to named routes. Scenario: access named route Given a file named "spec/routing/widget_routes_spec.rb" with: """ruby require "spec_helper" describe "routes to the widgets controller" do it "routes a named route" do expect(:get => new_widget_path). to route_to(:controller => "widgets", :action => "new") end end """ When I run `rspec spec` Then the examples should all pass rspec-rails-2.13.2/features/routing_specs/route_to_matcher.feature000066400000000000000000000053661214604200000254440ustar00rootroot00000000000000Feature: route_to matcher The `route_to` matcher specifies that a request (verb + path) is routable. It is most valuable when specifying routes other than standard RESTful routes. expect(get("/")).to route_to("welcome#index") # new in 2.6.0 or expect(:get => "/").to route_to(:controller => "welcome") Scenario: passing route spec with shortcut syntax Given a file named "spec/routing/widgets_routing_spec.rb" with: """ruby require "spec_helper" describe "routes for Widgets" do it "routes /widgets to the widgets controller" do expect(get("/widgets")). to route_to("widgets#index") end end """ When I run `rspec spec/routing/widgets_routing_spec.rb` Then the examples should all pass Scenario: passing route spec with verbose syntax Given a file named "spec/routing/widgets_routing_spec.rb" with: """ruby require "spec_helper" describe "routes for Widgets" do it "routes /widgets to the widgets controller" do expect(:get => "/widgets"). to route_to(:controller => "widgets", :action => "index") end end """ When I run `rspec spec/routing/widgets_routing_spec.rb` Then the examples should all pass Scenario: route spec for a route that doesn't exist (fails) Given a file named "spec/routing/widgets_routing_spec.rb" with: """ruby require "spec_helper" describe "routes for Widgets" do it "routes /widgets/foo to the /foo action" do expect(get("/widgets/foo")).to route_to("widgets#foo") end end """ When I run `rspec spec/routing/widgets_routing_spec.rb` Then the output should contain "1 failure" Scenario: route spec for a namespaced route with shortcut specifier Given a file named "spec/routing/admin_routing_spec.rb" with: """ruby require "spec_helper" describe "routes for Widgets" do it "routes /admin/accounts to the admin/accounts controller" do expect(get("/admin/accounts")). to route_to("admin/accounts#index") end end """ When I run `rspec spec/routing/admin_routing_spec.rb` Then the examples should all pass Scenario: route spec for a namespaced route with verbose specifier Given a file named "spec/routing/admin_routing_spec.rb" with: """ruby require "spec_helper" describe "routes for Widgets" do it "routes /admin/accounts to the admin/accounts controller" do expect(get("/admin/accounts")). to route_to(:controller => "admin/accounts", :action => "index") end end """ When I run `rspec spec/routing/admin_routing_spec.rb` Then the examples should all pass rspec-rails-2.13.2/features/step_definitions/000077500000000000000000000000001214604200000211745ustar00rootroot00000000000000rspec-rails-2.13.2/features/step_definitions/additional_cli_steps.rb000066400000000000000000000002231214604200000256730ustar00rootroot00000000000000Then /^the example(s)? should( all)? pass$/ do |_, _| step %q{the output should contain "0 failures"} step %q{the exit status should be 0} end rspec-rails-2.13.2/features/step_definitions/model_steps.rb000066400000000000000000000001161214604200000240350ustar00rootroot00000000000000Given /a (\w+) model/ do |model_class_name| puts eval(model_class_name) end rspec-rails-2.13.2/features/support/000077500000000000000000000000001214604200000173425ustar00rootroot00000000000000rspec-rails-2.13.2/features/support/env.rb000066400000000000000000000020611214604200000204560ustar00rootroot00000000000000require 'aruba/cucumber' module ArubaExt def run(cmd) super(cmd =~ /^rspec/ ? "bin/#{cmd}" : cmd) end end World(ArubaExt) Before do @aruba_timeout_seconds = 30 end unless File.directory?('./tmp/example_app') system "rake generate:app generate:stuff" end def aruba_path(file_or_dir) File.expand_path("../../../#{file_or_dir.sub('example_app','aruba')}", __FILE__) end def example_app_path(file_or_dir) File.expand_path("../../../#{file_or_dir}", __FILE__) end def write_symlink(file_or_dir) source = example_app_path(file_or_dir) target = aruba_path(file_or_dir) system "ln -s #{source} #{target}" end def copy(file_or_dir) source = example_app_path(file_or_dir) target = aruba_path(file_or_dir) system "cp -r #{source} #{target}" end Before do steps %Q{ Given a directory named "spec" } Dir['tmp/example_app/*'].each do |file_or_dir| if !(file_or_dir =~ /spec$/) write_symlink(file_or_dir) end end ["spec/spec_helper.rb"].each do |file_or_dir| write_symlink("tmp/example_app/#{file_or_dir}") end end rspec-rails-2.13.2/features/support/rails_versions.rb000066400000000000000000000002121214604200000227240ustar00rootroot00000000000000Around "@unsupported-on-rails-3-0" do |scenario, block| require 'rails' block.call unless ::Rails.version.to_s.start_with?("3.0") end rspec-rails-2.13.2/features/view_specs/000077500000000000000000000000001214604200000177755ustar00rootroot00000000000000rspec-rails-2.13.2/features/view_specs/inferred_controller_path.feature000066400000000000000000000024641214604200000264350ustar00rootroot00000000000000Feature: view spec infers controller path and action Scenario: infer controller path Given a file named "spec/views/widgets/new.html.erb_spec.rb" with: """ruby require "spec_helper" describe "widgets/new" do it "infers the controller path" do expect(controller.request.path_parameters[:controller]).to eq("widgets") expect(controller.controller_path).to eq("widgets") end end """ When I run `rspec spec/views` Then the examples should all pass Scenario: infer action Given a file named "spec/views/widgets/new.html.erb_spec.rb" with: """ruby require "spec_helper" describe "widgets/new" do it "infers the controller path" do expect(controller.request.path_parameters[:action]).to eq("new") end end """ When I run `rspec spec/views` Then the examples should all pass Scenario: do not infer action in a partial Given a file named "spec/views/widgets/_form.html.erb_spec.rb" with: """ruby require "spec_helper" describe "widgets/_form" do it "includes a link to new" do expect(controller.request.path_parameters[:action]).to be_nil end end """ When I run `rspec spec/views` Then the examples should all pass rspec-rails-2.13.2/features/view_specs/stub_template.feature000066400000000000000000000031521214604200000242230ustar00rootroot00000000000000Feature: stub template In order to isolate view specs from the partials rendered by the primary view, rspec-rails (since 2.2) provides the stub_template method. Scenario: stub template that does not exist Given a file named "spec/views/gadgets/list.html.erb_spec.rb" with: """ruby require "spec_helper" describe "gadgets/list" do it "renders the gadget partial for each gadget" do assign(:gadgets, [ mock_model(Gadget, :id => 1, :name => "First"), mock_model(Gadget, :id => 2, :name => "Second") ]) stub_template "gadgets/_gadget.html.erb" => "<%= gadget.name %>
" render expect(rendered).to match /First/ expect(rendered).to match /Second/ end end """ And a file named "app/views/gadgets/list.html.erb" with: """ <%= render :partial => "gadget", :collection => @gadgets %> """ When I run `rspec spec/views/gadgets/list.html.erb_spec.rb` Then the examples should all pass Scenario: stub template that exists Given a file named "spec/views/gadgets/edit.html.erb_spec.rb" with: """ruby require "spec_helper" describe "gadgets/edit" do before(:each) do @gadget = assign(:gadget, stub_model(Gadget)) end it "renders the form partial" do stub_template "gadgets/_form.html.erb" => "This content" render expect(rendered).to match /This content/ end end """ When I run `rspec spec/views/gadgets/edit.html.erb_spec.rb` Then the examples should all pass rspec-rails-2.13.2/features/view_specs/view_spec.feature000066400000000000000000000133461214604200000233450ustar00rootroot00000000000000Feature: view spec View specs live in spec/views and render view templates in isolation. Scenario: passing spec that renders the described view file Given a file named "spec/views/widgets/index.html.erb_spec.rb" with: """ruby require "spec_helper" describe "widgets/index" do it "displays all the widgets" do assign(:widgets, [ stub_model(Widget, :name => "slicer"), stub_model(Widget, :name => "dicer") ]) render expect(rendered).to match /slicer/ expect(rendered).to match /dicer/ end end """ When I run `rspec spec/views` Then the examples should all pass Scenario: passing spec with before and nesting Given a file named "spec/views/widgets/index.html.erb_spec.rb" with: """ruby require "spec_helper" describe "widgets/index" do context "with 2 widgets" do before(:each) do assign(:widgets, [ stub_model(Widget, :name => "slicer"), stub_model(Widget, :name => "dicer") ]) end it "displays both widgets" do render expect(rendered).to match /slicer/ expect(rendered).to match /dicer/ end end end """ When I run `rspec spec/views` Then the examples should all pass Scenario: passing spec with explicit template rendering Given a file named "spec/views/widgets/widget.html.erb_spec.rb" with: """ruby require "spec_helper" describe "rendering the widget template" do it "displays the widget" do assign(:widget, stub_model(Widget, :name => "slicer")) render :template => "widgets/widget.html.erb" expect(rendered).to match /slicer/ end end """ And a file named "app/views/widgets/widget.html.erb" with: """

<%= @widget.name %>

""" When I run `rspec spec/views` Then the examples should all pass Scenario: passing spec with a description that includes the format and handler Given a file named "spec/views/widgets/widget.xml.erb_spec.rb" with: """ruby require "spec_helper" describe "widgets/widget.html.erb" do it "renders the HTML template" do render expect(rendered).to match /HTML/ end end describe "widgets/widget.xml.erb" do it "renders the XML template" do render expect(rendered).to match /XML/ end end """ And a file named "app/views/widgets/widget.html.erb" with: """ HTML """ And a file named "app/views/widgets/widget.xml.erb" with: """ XML """ When I run `rspec spec/views` Then the examples should all pass Scenario: passing spec with rendering of locals in a partial Given a file named "spec/views/widgets/_widget.html.erb_spec.rb" with: """ruby require "spec_helper" describe "rendering locals in a partial" do it "displays the widget" do widget = stub_model(Widget, :name => "slicer") render :partial => "widgets/widget.html.erb", :locals => {:widget => widget} expect(rendered).to match /slicer/ end end """ And a file named "app/views/widgets/_widget.html.erb" with: """

<%= widget.name %>

""" When I run `rspec spec/views` Then the examples should all pass Scenario: passing spec with rendering of locals in an implicit partial Given a file named "spec/views/widgets/_widget.html.erb_spec.rb" with: """ruby require "spec_helper" describe "rendering locals in a partial" do it "displays the widget" do widget = stub_model(Widget, :name => "slicer") render "widgets/widget", :widget => widget expect(rendered).to match /slicer/ end end """ And a file named "app/views/widgets/_widget.html.erb" with: """

<%= widget.name %>

""" When I run `rspec spec/views` Then the examples should all pass Scenario: passing spec with rendering of text Given a file named "spec/views/widgets/direct.html.erb_spec.rb" with: """ruby require "spec_helper" describe "rendering text directly" do it "displays the given text" do render :text => "This is directly rendered" expect(rendered).to match /directly rendered/ end end """ When I run `rspec spec/views` Then the examples should all pass Scenario: passing view spec that stubs a helper method Given a file named "app/views/secrets/index.html.erb" with: """ <%- if admin? %>

Secret admin area

<%- end %> """ And a file named "spec/views/secrets/index.html.erb_spec.rb" with: """ruby require 'spec_helper' describe 'secrets/index' do before do view.stub(:admin?).and_return(true) end it 'checks for admin access' do render expect(rendered).to match /Secret admin area/ end end """ When I run `rspec spec/views/secrets` Then the examples should all pass Scenario: request.path_parameters should match Rails by using symbols for keys Given a file named "spec/views/widgets/index.html.erb_spec.rb" with: """ruby require "spec_helper" describe "controller.request.path_parameters" do it "matches the Rails environment by using symbols for keys" do [:controller, :action].each { |k| expect(controller.request.path_parameters.keys).to include(k) } end end """ When I run `rspec spec/views` Then the examples should all pass rspec-rails-2.13.2/lib/000077500000000000000000000000001214604200000145565ustar00rootroot00000000000000rspec-rails-2.13.2/lib/autotest/000077500000000000000000000000001214604200000164265ustar00rootroot00000000000000rspec-rails-2.13.2/lib/autotest/rails_rspec2.rb000066400000000000000000000061031214604200000213430ustar00rootroot00000000000000# (c) Copyright 2006 Nick Sieger # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. $:.push(*Dir["vendor/rails/*/lib"]) require 'active_support/core_ext' require 'autotest/rspec2' class Autotest::RailsRspec2 < Autotest::Rspec2 def initialize super setup_rails_rspec2_mappings end def setup_rails_rspec2_mappings %w{coverage/ db/ doc/ log/ public/ script/ tmp/ vendor/rails vendor/plugins vendor/gems}.each do |exception| add_exception(/^([\.\/]*)?#{exception}/) end clear_mappings add_mapping(%r%^(test|spec)/fixtures/(.*).yml$%) { |_, m| ["spec/models/#{m[2].singularize}_spec.rb"] + files_matching(%r%^spec\/views\/#{m[2]}/.*_spec\.rb$%) } add_mapping(%r%^spec/.*_spec\.rb$%) { |filename, _| filename } add_mapping(%r%^app/models/(.*)\.rb$%) { |_, m| ["spec/models/#{m[1]}_spec.rb"] } add_mapping(%r%^app/views/(.*)$%) { |_, m| files_matching %r%^spec/views/#{m[1]}_spec.rb$% } add_mapping(%r%^app/controllers/(.*)\.rb$%) { |_, m| if m[1] == "application" files_matching %r%^spec/controllers/.*_spec\.rb$% else ["spec/controllers/#{m[1]}_spec.rb"] end } add_mapping(%r%^app/helpers/(.*)_helper\.rb$%) { |_, m| if m[1] == "application" then files_matching(%r%^spec/(views|helpers)/.*_spec\.rb$%) else ["spec/helpers/#{m[1]}_helper_spec.rb"] + files_matching(%r%^spec\/views\/#{m[1]}/.*_spec\.rb$%) end } add_mapping(%r%^config/routes\.rb$%) { files_matching %r%^spec/(controllers|routing|views|helpers)/.*_spec\.rb$% } add_mapping(%r%^config/database\.yml$%) { |_, m| files_matching %r%^spec/models/.*_spec\.rb$% } add_mapping(%r%^(spec/(spec_helper|support/.*)|config/(boot|environment(s/test)?))\.rb$%) { files_matching %r%^spec/(models|controllers|routing|views|helpers)/.*_spec\.rb$% } add_mapping(%r%^lib/(.*)\.rb$%) { |_, m| ["spec/lib/#{m[1]}_spec.rb"] } add_mapping(%r%^app/mailers/(.*)\.rb$%) { |_, m| ["spec/mailers/#{m[1]}_spec.rb"] } end end rspec-rails-2.13.2/lib/generators/000077500000000000000000000000001214604200000167275ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec.rb000066400000000000000000000012021214604200000203630ustar00rootroot00000000000000require 'rails/generators/named_base' module Rspec module Generators class Base < ::Rails::Generators::NamedBase def self.source_root @_rspec_source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'rspec', generator_name, 'templates')) end if ::Rails::VERSION::STRING < '3.1' def module_namespacing yield if block_given? end end end end end module Rails module Generators class GeneratedAttribute def input_type @input_type ||= if type == :text "textarea" else "input" end end end end end rspec-rails-2.13.2/lib/generators/rspec/000077500000000000000000000000001214604200000200435ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/controller/000077500000000000000000000000001214604200000222265ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/controller/controller_generator.rb000066400000000000000000000021101214604200000267760ustar00rootroot00000000000000require '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" class_option :controller_specs, :type => :boolean, :default => true class_option :view_specs, :type => :boolean, :default => true def generate_controller_spec return unless options[:controller_specs] template 'controller_spec.rb', File.join('spec/controllers', class_path, "#{file_name}_controller_spec.rb") end def generate_view_specs return if actions.empty? return unless options[:view_specs] && options[:template_engine] 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 rspec-rails-2.13.2/lib/generators/rspec/controller/templates/000077500000000000000000000000001214604200000242245ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/controller/templates/controller_spec.rb000066400000000000000000000004431214604200000277470ustar00rootroot00000000000000require 'spec_helper' <% module_namespacing do -%> describe <%= class_name %>Controller do <% for action in actions -%> describe "GET '<%= action %>'" do it "returns http success" do get '<%= action %>' response.should be_success end end <% end -%> end <% end -%> rspec-rails-2.13.2/lib/generators/rspec/controller/templates/view_spec.rb000066400000000000000000000002501214604200000265320ustar00rootroot00000000000000require 'spec_helper' describe "<%= file_name %>/<%= @action %>.html.<%= options[:template_engine] %>" do pending "add some examples to (or delete) #{__FILE__}" end rspec-rails-2.13.2/lib/generators/rspec/helper/000077500000000000000000000000001214604200000213225ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/helper/helper_generator.rb000066400000000000000000000005661214604200000252030ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators class HelperGenerator < Base class_option :helper_specs, :type => :boolean, :default => true def generate_helper_spec return unless options[:helper_specs] template 'helper_spec.rb', File.join('spec/helpers', class_path, "#{file_name}_helper_spec.rb") end end end end rspec-rails-2.13.2/lib/generators/rspec/helper/templates/000077500000000000000000000000001214604200000233205ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/helper/templates/helper_spec.rb000066400000000000000000000007371214604200000261450ustar00rootroot00000000000000require 'spec_helper' # Specs in this file have access to a helper object that includes # the <%= class_name %>Helper. For example: # # describe <%= class_name %>Helper do # describe "string concat" do # it "concats two strings with spaces" do # helper.concat_strings("this","that").should == "this that" # end # end # end <% module_namespacing do -%> describe <%= class_name %>Helper do pending "add some examples to (or delete) #{__FILE__}" end <% end -%> rspec-rails-2.13.2/lib/generators/rspec/install/000077500000000000000000000000001214604200000215115ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/install/install_generator.rb000066400000000000000000000006661214604200000255620ustar00rootroot00000000000000module Rspec module Generators class InstallGenerator < ::Rails::Generators::Base desc <= '4' -%> # Checks for pending migrations before tests are run. # If you are not using ActiveRecord, you can remove this line. ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration) <% end -%> RSpec.configure do |config| # ## Mock Framework # # 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 # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true # If true, the base class of anonymous controllers will be inferred # automatically. This will be the default behavior in future versions of # rspec-rails. config.infer_base_class_for_anonymous_controllers = false # 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 rspec-rails-2.13.2/lib/generators/rspec/integration/000077500000000000000000000000001214604200000223665ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/integration/integration_generator.rb000066400000000000000000000016411214604200000273060ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators class IntegrationGenerator < Base class_option :request_specs, :type => :boolean, :default => true, :desc => "Generate request specs" class_option :webrat, :type => :boolean, :default => false, :desc => "Use webrat methods/matchers" class_option :webrat_matchers, :type => :boolean, :default => false, :desc => "Use webrat methods/matchers (deprecated - use --webrat)" def generate_request_spec return unless options[:request_specs] template 'request_spec.rb', File.join('spec/requests', class_path, "#{table_name}_spec.rb") end protected # @deprecated Use `--webrat` instead. def webrat? RSpec.deprecate("the --webrat-matchers option", "--webrat") if options[:webrat_matchers] options[:webrat] || options[:webrat_matchers] end end end end rspec-rails-2.13.2/lib/generators/rspec/integration/templates/000077500000000000000000000000001214604200000243645ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/integration/templates/request_spec.rb000066400000000000000000000006411214604200000274140ustar00rootroot00000000000000require 'spec_helper' describe "<%= class_name.pluralize %>" do describe "GET /<%= table_name %>" do it "works! (now write some real specs)" do <% if webrat? -%> visit <%= index_helper %>_path <% else -%> # Run the generator again with the --webrat flag if you want to use webrat methods/matchers get <%= index_helper %>_path <% end -%> response.status.should be(200) end end end rspec-rails-2.13.2/lib/generators/rspec/mailer/000077500000000000000000000000001214604200000213145ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/mailer/mailer_generator.rb000066400000000000000000000010521214604200000251560ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators class MailerGenerator < Base argument :actions, :type => :array, :default => [], :banner => "method method" def generate_mailer_spec template "mailer_spec.rb", File.join('spec/mailers', class_path, "#{file_name}_spec.rb") end def generate_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 rspec-rails-2.13.2/lib/generators/rspec/mailer/templates/000077500000000000000000000000001214604200000233125ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/mailer/templates/fixture000066400000000000000000000001101214604200000247130ustar00rootroot00000000000000<%= class_name %>#<%= @action %> Hi, find me in app/views/<%= @path %> rspec-rails-2.13.2/lib/generators/rspec/mailer/templates/mailer_spec.rb000066400000000000000000000011261214604200000261220ustar00rootroot00000000000000require "spec_helper" <% module_namespacing do -%> describe <%= class_name %> do <% for action in actions -%> describe "<%= action %>" do let(:mail) { <%= class_name %>.<%= action %> } it "renders the headers" do mail.subject.should eq(<%= action.to_s.humanize.inspect %>) mail.to.should eq(["to@example.org"]) mail.from.should eq(["from@example.com"]) end it "renders the body" do mail.body.encoded.should match("Hi") end end <% end -%> <% if actions.blank? -%> pending "add some examples to (or delete) #{__FILE__}" <% end -%> end <% end -%> rspec-rails-2.13.2/lib/generators/rspec/model/000077500000000000000000000000001214604200000211435ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/model/model_generator.rb000066400000000000000000000011641214604200000246400ustar00rootroot00000000000000require '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_model_spec 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 rspec-rails-2.13.2/lib/generators/rspec/model/templates/000077500000000000000000000000001214604200000231415ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/model/templates/fixtures.yml000066400000000000000000000006161214604200000255400ustar00rootroot00000000000000# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/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 -%> rspec-rails-2.13.2/lib/generators/rspec/model/templates/model_spec.rb000077500000000000000000000002321214604200000256000ustar00rootroot00000000000000require 'spec_helper' <% module_namespacing do -%> describe <%= class_name %> do pending "add some examples to (or delete) #{__FILE__}" end <% end -%> rspec-rails-2.13.2/lib/generators/rspec/observer/000077500000000000000000000000001214604200000216725ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/observer/observer_generator.rb000066400000000000000000000004341214604200000261150ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators class ObserverGenerator < Base def generate_observer_spec template 'observer_spec.rb', File.join('spec', 'models', class_path, "#{file_name}_observer_spec.rb") end end end end rspec-rails-2.13.2/lib/generators/rspec/observer/templates/000077500000000000000000000000001214604200000236705ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/observer/templates/observer_spec.rb000066400000000000000000000002421214604200000270540ustar00rootroot00000000000000require 'spec_helper' <% module_namespacing do -%> describe <%= class_name %>Observer do pending "add some examples to (or delete) #{__FILE__}" end <% end -%> rspec-rails-2.13.2/lib/generators/rspec/scaffold/000077500000000000000000000000001214604200000216245ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/scaffold/scaffold_generator.rb000066400000000000000000000150621214604200000260040ustar00rootroot00000000000000require 'generators/rspec' require 'rails/generators/resource_helpers' module Rspec module Generators class ScaffoldGenerator < Base include ::Rails::Generators::ResourceHelpers source_paths << File.expand_path("../../helper/templates", __FILE__) 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 :controller_specs, :type => :boolean, :default => true, :desc => "Generate controller specs" class_option :view_specs, :type => :boolean, :default => true, :desc => "Generate view specs" class_option :webrat, :type => :boolean, :default => false, :desc => "Use webrat methods/matchers" class_option :webrat_matchers, :type => :boolean, :default => false, :desc => "Use webrat methods/matchers (deprecated - use --webrat)" class_option :helper_specs, :type => :boolean, :default => true, :desc => "Generate helper specs" class_option :routing_specs, :type => :boolean, :default => true, :desc => "Generate routing specs" def generate_controller_spec return unless options[:controller_specs] template 'controller_spec.rb', File.join('spec/controllers', controller_class_path, "#{controller_file_name}_controller_spec.rb") end def generate_view_specs return unless options[:view_specs] && options[:template_engine] copy_view :edit copy_view :index unless options[:singleton] copy_view :new copy_view :show end def generate_routing_spec return unless options[:routing_specs] 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 # @deprecated Use `--webrat` instead. def webrat? RSpec.deprecate("--webrat-matchers", "--webrat") if options[:webrat_matchers] options[:webrat] || options[:webrat_matchers] end def copy_view(view) template "#{view}_spec.rb", File.join("spec/views", controller_file_path, "#{view}.html.#{options[:template_engine]}_spec.rb") end def example_valid_attributes # Only take the first attribute so this hash does not become unweildy and large in the # generated controller spec. It is the responsibility of the user to keep the the valid # attributes method up-to-date as they add validations. @example_valid_attributes ||= if attributes.any? { attributes.first.name => attributes.first.default.to_s } else { } end end def example_invalid_attributes @example_invalid_attributes ||= if attributes.any? { attributes.first.name => "invalid value" } else { } end end def example_params_for_update @example_params_for_update ||= if example_valid_attributes.any? example_valid_attributes else { "these" => "params" } end end def formatted_hash(hash) formatted = hash.inspect formatted.gsub!("{", "{ ") formatted.gsub!("}", " }") formatted.gsub!("=>", " => ") formatted end # support for namespaced-resources def ns_file_name ns_parts.empty? ? file_name : "#{ns_parts[0].underscore}_#{ns_parts[1].singularize.underscore}" end # support for namespaced-resources def ns_table_name ns_parts.empty? ? table_name : "#{ns_parts[0].underscore}/#{ns_parts[1].tableize}" end def ns_parts @ns_parts ||= begin matches = ARGV[0].to_s.match(/\A(\w+)(?:\/|::)(\w+)/) matches ? [matches[1], matches[2]] : [] end 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_#{ns_file_name}(:#{method} => #{and_return})" else "mock_#{ns_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_receive(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 def value_for(attribute) case attribute.type when :string "#{attribute.name.titleize}".inspect when :integer @attribute_id_map ||= {} @attribute_id_map[attribute] ||= @attribute_id_map.keys.size.next.to_s else attribute.default.inspect end end def banner self.class.banner end end end end rspec-rails-2.13.2/lib/generators/rspec/scaffold/templates/000077500000000000000000000000001214604200000236225ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/scaffold/templates/controller_spec.rb000066400000000000000000000170241214604200000273500ustar00rootroot00000000000000require 'spec_helper' # This spec was generated by rspec-rails when you ran the scaffold generator. # It demonstrates how one might use RSpec to specify the controller code that # was generated by Rails when you ran the scaffold generator. # # It assumes that the implementation code is generated by the rails scaffold # generator. If you are using any extension libraries to generate different # controller code, this generated spec may or may not pass. # # It only uses APIs available in rails and/or rspec-rails. There are a number # of tools you can use to make these specs even more expressive, but we're # sticking to rails and rspec-rails APIs to keep things simple and stable. # # Compared to earlier versions of this generator, there is very limited use of # stubs and message expectations in this spec. Stubs are only used when there # is no simpler way to get a handle on the object needed for the example. # Message expectations are only used when there is no simpler way to specify # that an instance is receiving a specific message. <% module_namespacing do -%> describe <%= controller_class_name %>Controller do # This should return the minimal set of attributes required to create a valid # <%= class_name %>. As you add validations to <%= class_name %>, be sure to # adjust the attributes here as well. let(:valid_attributes) { <%= formatted_hash(example_valid_attributes) %> } # This should return the minimal set of values that should be in the session # in order to pass any filters (e.g. authentication) defined in # <%= controller_class_name %>Controller. Be sure to keep this updated too. let(:valid_session) { {} } <% unless options[:singleton] -%> describe "GET index" do it "assigns all <%= table_name.pluralize %> as @<%= table_name.pluralize %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes get :index, {}, valid_session assigns(:<%= table_name %>).should eq([<%= file_name %>]) end end <% end -%> describe "GET show" do it "assigns the requested <%= ns_file_name %> as @<%= ns_file_name %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes get :show, {:id => <%= file_name %>.to_param}, valid_session assigns(:<%= ns_file_name %>).should eq(<%= file_name %>) end end describe "GET new" do it "assigns a new <%= ns_file_name %> as @<%= ns_file_name %>" do get :new, {}, valid_session assigns(:<%= ns_file_name %>).should be_a_new(<%= class_name %>) end end describe "GET edit" do it "assigns the requested <%= ns_file_name %> as @<%= ns_file_name %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes get :edit, {:id => <%= file_name %>.to_param}, valid_session assigns(:<%= ns_file_name %>).should eq(<%= file_name %>) end end describe "POST create" do describe "with valid params" do it "creates a new <%= class_name %>" do expect { post :create, {:<%= ns_file_name %> => valid_attributes}, valid_session }.to change(<%= class_name %>, :count).by(1) end it "assigns a newly created <%= ns_file_name %> as @<%= ns_file_name %>" do post :create, {:<%= ns_file_name %> => valid_attributes}, valid_session assigns(:<%= ns_file_name %>).should be_a(<%= class_name %>) assigns(:<%= ns_file_name %>).should be_persisted end it "redirects to the created <%= ns_file_name %>" do post :create, {:<%= ns_file_name %> => valid_attributes}, valid_session response.should redirect_to(<%= class_name %>.last) end end describe "with invalid params" do it "assigns a newly created but unsaved <%= ns_file_name %> as @<%= ns_file_name %>" do # Trigger the behavior that occurs when invalid params are submitted <%= class_name %>.any_instance.stub(:save).and_return(false) post :create, {:<%= ns_file_name %> => <%= formatted_hash(example_invalid_attributes) %>}, valid_session assigns(:<%= ns_file_name %>).should be_a_new(<%= class_name %>) end it "re-renders the 'new' template" do # Trigger the behavior that occurs when invalid params are submitted <%= class_name %>.any_instance.stub(:save).and_return(false) post :create, {:<%= ns_file_name %> => <%= formatted_hash(example_invalid_attributes) %>}, valid_session response.should render_template("new") end end end describe "PUT update" do describe "with valid params" do it "updates the requested <%= ns_file_name %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes # Assuming there are no other <%= table_name %> in the database, this # specifies that the <%= class_name %> created on the previous line # receives the :update_attributes message with whatever params are # submitted in the request. <%- if ::Rails::VERSION::STRING >= '4' -%> <%= class_name %>.any_instance.should_receive(:update).with(<%= formatted_hash(example_params_for_update) %>) <%- else -%> <%= class_name %>.any_instance.should_receive(:update_attributes).with(<%= formatted_hash(example_params_for_update) %>) <%- end -%> put :update, {:id => <%= file_name %>.to_param, :<%= ns_file_name %> => <%= formatted_hash(example_params_for_update) %>}, valid_session end it "assigns the requested <%= ns_file_name %> as @<%= ns_file_name %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes put :update, {:id => <%= file_name %>.to_param, :<%= ns_file_name %> => valid_attributes}, valid_session assigns(:<%= ns_file_name %>).should eq(<%= file_name %>) end it "redirects to the <%= ns_file_name %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes put :update, {:id => <%= file_name %>.to_param, :<%= ns_file_name %> => valid_attributes}, valid_session response.should redirect_to(<%= file_name %>) end end describe "with invalid params" do it "assigns the <%= ns_file_name %> as @<%= ns_file_name %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes # Trigger the behavior that occurs when invalid params are submitted <%= class_name %>.any_instance.stub(:save).and_return(false) put :update, {:id => <%= file_name %>.to_param, :<%= ns_file_name %> => <%= formatted_hash(example_invalid_attributes) %>}, valid_session assigns(:<%= ns_file_name %>).should eq(<%= file_name %>) end it "re-renders the 'edit' template" do <%= file_name %> = <%= class_name %>.create! valid_attributes # Trigger the behavior that occurs when invalid params are submitted <%= class_name %>.any_instance.stub(:save).and_return(false) put :update, {:id => <%= file_name %>.to_param, :<%= ns_file_name %> => <%= formatted_hash(example_invalid_attributes) %>}, valid_session response.should render_template("edit") end end end describe "DELETE destroy" do it "destroys the requested <%= ns_file_name %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes expect { delete :destroy, {:id => <%= file_name %>.to_param}, valid_session }.to change(<%= class_name %>, :count).by(-1) end it "redirects to the <%= table_name %> list" do <%= file_name %> = <%= class_name %>.create! valid_attributes delete :destroy, {:id => <%= file_name %>.to_param}, valid_session response.should redirect_to(<%= index_helper %>_url) end end end <% end -%> rspec-rails-2.13.2/lib/generators/rspec/scaffold/templates/edit_spec.rb000066400000000000000000000026741214604200000261170ustar00rootroot00000000000000require 'spec_helper' <% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%> describe "<%= ns_table_name %>/edit" do before(:each) do @<%= ns_file_name %> = assign(:<%= ns_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 -%> <%= output_attributes.empty? ? "" : " ))\n" -%> end it "renders the edit <%= ns_file_name %> form" do render <% if webrat? -%> rendered.should have_selector("form", :action => <%= ns_file_name %>_path(@<%= ns_file_name %>), :method => "post") do |form| <% for attribute in output_attributes -%> form.should have_selector("<%= attribute.input_type -%>#<%= ns_file_name %>_<%= attribute.name %>", :name => "<%= ns_file_name %>[<%= attribute.name %>]") <% end -%> end <% else -%> # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form[action=?][method=?]", <%= ns_file_name %>_path(@<%= ns_file_name %>), "post" do <% for attribute in output_attributes -%> assert_select "<%= attribute.input_type -%>#<%= ns_file_name %>_<%= attribute.name %>[name=?]", "<%= ns_file_name %>[<%= attribute.name %>]" <% end -%> end <% end -%> end end rspec-rails-2.13.2/lib/generators/rspec/scaffold/templates/index_spec.rb000066400000000000000000000022411214604200000262670ustar00rootroot00000000000000require 'spec_helper' <% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%> describe "<%= ns_table_name %>/index" do before(:each) do assign(:<%= 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 %> => <%= value_for(attribute) %><%= attribute_index == output_attributes.length - 1 ? '' : ','%> <% end -%> <% if !output_attributes.empty? -%> <%= model_index == 1 ? ')' : '),' %> <% end -%> <% end -%> ]) end it "renders a list of <%= ns_table_name %>" do render <% unless webrat? -%> # Run the generator again with the --webrat flag if you want to use webrat matchers <% end -%> <% for attribute in output_attributes -%> <% if webrat? -%> rendered.should have_selector("tr>td", :content => <%= value_for(attribute) %>.to_s, :count => 2) <% else -%> assert_select "tr>td", :text => <%= value_for(attribute) %>.to_s, :count => 2 <% end -%> <% end -%> end end rspec-rails-2.13.2/lib/generators/rspec/scaffold/templates/new_spec.rb000066400000000000000000000026211214604200000257530ustar00rootroot00000000000000require 'spec_helper' <% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%> describe "<%= ns_table_name %>/new" do before(:each) do assign(:<%= ns_file_name %>, stub_model(<%= class_name %><%= output_attributes.empty? ? ').as_new_record)' : ',' %> <% output_attributes.each_with_index do |attribute, attribute_index| -%> :<%= attribute.name %> => <%= attribute.default.inspect %><%= attribute_index == output_attributes.length - 1 ? '' : ','%> <% end -%> <%= !output_attributes.empty? ? " ).as_new_record)\n end" : " end" %> it "renders new <%= ns_file_name %> form" do render <% if webrat? -%> rendered.should have_selector("form", :action => <%= table_name %>_path, :method => "post") do |form| <% for attribute in output_attributes -%> form.should have_selector("<%= attribute.input_type -%>#<%= ns_file_name %>_<%= attribute.name %>", :name => "<%= ns_file_name %>[<%= attribute.name %>]") <% end -%> end <% else -%> # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form[action=?][method=?]", <%= index_helper %>_path, "post" do <% for attribute in output_attributes -%> assert_select "<%= attribute.input_type -%>#<%= ns_file_name %>_<%= attribute.name %>[name=?]", "<%= ns_file_name %>[<%= attribute.name %>]" <% end -%> end <% end -%> end end rspec-rails-2.13.2/lib/generators/rspec/scaffold/templates/routing_spec.rb000066400000000000000000000021101214604200000266420ustar00rootroot00000000000000require "spec_helper" <% module_namespacing do -%> describe <%= controller_class_name %>Controller do describe "routing" do <% unless options[:singleton] -%> it "routes to #index" do get("/<%= ns_table_name %>").should route_to("<%= ns_table_name %>#index") end <% end -%> it "routes to #new" do get("/<%= ns_table_name %>/new").should route_to("<%= ns_table_name %>#new") end it "routes to #show" do get("/<%= ns_table_name %>/1").should route_to("<%= ns_table_name %>#show", :id => "1") end it "routes to #edit" do get("/<%= ns_table_name %>/1/edit").should route_to("<%= ns_table_name %>#edit", :id => "1") end it "routes to #create" do post("/<%= ns_table_name %>").should route_to("<%= ns_table_name %>#create") end it "routes to #update" do put("/<%= ns_table_name %>/1").should route_to("<%= ns_table_name %>#update", :id => "1") end it "routes to #destroy" do delete("/<%= ns_table_name %>/1").should route_to("<%= ns_table_name %>#destroy", :id => "1") end end end <% end -%> rspec-rails-2.13.2/lib/generators/rspec/scaffold/templates/show_spec.rb000066400000000000000000000017441214604200000261470ustar00rootroot00000000000000require 'spec_helper' <% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%> describe "<%= ns_table_name %>/show" do before(:each) do @<%= ns_file_name %> = assign(:<%= ns_file_name %>, stub_model(<%= class_name %><%= output_attributes.empty? ? '))' : ',' %> <% output_attributes.each_with_index do |attribute, attribute_index| -%> :<%= attribute.name %> => <%= value_for(attribute) %><%= attribute_index == output_attributes.length - 1 ? '' : ','%> <% end -%> <% if !output_attributes.empty? -%> )) <% end -%> end it "renders attributes in

" do render <% unless webrat? -%> # Run the generator again with the --webrat flag if you want to use webrat matchers <% end -%> <% for attribute in output_attributes -%> <% if webrat? -%> rendered.should contain(<%= value_for(attribute) %>.to_s) <% else -%> rendered.should match(/<%= eval(value_for(attribute)) %>/) <% end -%> <% end -%> end end rspec-rails-2.13.2/lib/generators/rspec/view/000077500000000000000000000000001214604200000210155ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/view/templates/000077500000000000000000000000001214604200000230135ustar00rootroot00000000000000rspec-rails-2.13.2/lib/generators/rspec/view/templates/view_spec.rb000066400000000000000000000002021214604200000253160ustar00rootroot00000000000000require 'spec_helper' describe "<%= file_path %>/<%= @action %>" do pending "add some examples to (or delete) #{__FILE__}" end rspec-rails-2.13.2/lib/generators/rspec/view/view_generator.rb000066400000000000000000000011351214604200000243620ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators class ViewGenerator < Base argument :actions, :type => :array, :default => [], :banner => "action action" class_option :template_engine, :desc => "Template engine to generate view files" def create_view_specs 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 rspec-rails-2.13.2/lib/rspec-rails.rb000066400000000000000000000006531214604200000173330ustar00rootroot00000000000000module RSpec module Rails class Railtie < ::Rails::Railtie # Rails-3.0.1 requires config.app_generators instead of 3.0.0's config.generators generators = config.respond_to?(:app_generators) ? config.app_generators : config.generators generators.integration_tool :rspec generators.test_framework :rspec rake_tasks do load "rspec/rails/tasks/rspec.rake" end end end end rspec-rails-2.13.2/lib/rspec/000077500000000000000000000000001214604200000156725ustar00rootroot00000000000000rspec-rails-2.13.2/lib/rspec/rails.rb000066400000000000000000000007771214604200000173440ustar00rootroot00000000000000require 'rspec/core' RSpec::configure do |c| c.backtrace_clean_patterns << /vendor\// c.backtrace_clean_patterns << /lib\/rspec\/rails/ end require 'rails/version' require 'rspec/rails/extensions' require 'rspec/rails/view_rendering' require 'rspec/rails/adapters' require 'rspec/rails/matchers' require 'rspec/rails/fixture_support' require 'rspec/rails/mocks' require 'rspec/rails/module_inclusion' require 'rspec/rails/example' require 'rspec/rails/vendor/capybara' require 'rspec/rails/vendor/webrat' rspec-rails-2.13.2/lib/rspec/rails/000077500000000000000000000000001214604200000170045ustar00rootroot00000000000000rspec-rails-2.13.2/lib/rspec/rails/adapters.rb000066400000000000000000000067201214604200000211410ustar00rootroot00000000000000require 'delegate' require 'active_support/concern' require 'test/unit/assertions' module RSpec module Rails class AssertionDelegator < Module # @api private def initialize(*assertion_modules) assertion_class = Class.new(SimpleDelegator) do include Test::Unit::Assertions assertion_modules.each { |mod| include mod } end super() do # @api private define_method :build_assertion_instance do assertion_class.new(self) end # @api private def assertion_instance @assertion_instance ||= build_assertion_instance end assertion_modules.each do |mod| mod.public_instance_methods.each do |method| next if method == :method_missing || method == "method_missing" class_eval <<-EOM, __FILE__, __LINE__ + 1 def #{method}(*args, &block) assertion_instance.send(:#{method}, *args, &block) end EOM end end end end end # MiniTest::Unit::LifecycleHooks module MiniTestLifecycleAdapter extend ActiveSupport::Concern included do |group| group.before { after_setup } group.after { before_teardown } group.around do |example| before_setup example.run after_teardown end end def before_setup end def after_setup end def before_teardown end def after_teardown end end module SetupAndTeardownAdapter extend ActiveSupport::Concern module ClassMethods # @api private # # Wraps `setup` calls from within Rails' testing framework in `before` # hooks. def setup(*methods) methods.each do |method| if method.to_s =~ /^setup_(fixtures|controller_request_and_response)$/ prepend_before { send method } else before { send method } end end end # @api private # # Wraps `teardown` calls from within Rails' testing framework in # `after` hooks. def teardown(*methods) methods.each { |method| after { send method } } end end # @api private def method_name @example end end module TestUnitAssertionAdapter extend ActiveSupport::Concern module ClassMethods # @api private # # Returns the names of assertion methods that we want to expose to # examples without exposing non-assertion methods in Test::Unit or # Minitest. def assertion_method_names Test::Unit::Assertions.public_instance_methods.select{|m| m.to_s =~ /^(assert|flunk)/} + [:build_message] end # @api private def define_assertion_delegators assertion_method_names.each do |m| class_eval <<-CODE, __FILE__, __LINE__ + 1 def #{m}(*args, &block) assertion_delegator.send :#{m}, *args, &block end CODE end end end class AssertionDelegator include Test::Unit::Assertions end # @api private def assertion_delegator @assertion_delegator ||= AssertionDelegator.new end included do define_assertion_delegators end end end end rspec-rails-2.13.2/lib/rspec/rails/example.rb000066400000000000000000000033641214604200000207720ustar00rootroot00000000000000require 'rspec/rails/example/rails_example_group' require 'rspec/rails/example/controller_example_group' require 'rspec/rails/example/request_example_group' require 'rspec/rails/example/helper_example_group' require 'rspec/rails/example/view_example_group' require 'rspec/rails/example/mailer_example_group' require 'rspec/rails/example/routing_example_group' require 'rspec/rails/example/model_example_group' require 'rspec/rails/example/feature_example_group' RSpec::configure do |c| def c.escaped_path(*parts) Regexp.compile(parts.join('[\\\/]') + '[\\\/]') end c.include RSpec::Rails::ControllerExampleGroup, :type => :controller, :example_group => { :file_path => c.escaped_path(%w[spec controllers]) } c.include RSpec::Rails::HelperExampleGroup, :type => :helper, :example_group => { :file_path => c.escaped_path(%w[spec helpers]) } if defined?(RSpec::Rails::MailerExampleGroup) c.include RSpec::Rails::MailerExampleGroup, :type => :mailer, :example_group => { :file_path => c.escaped_path(%w[spec mailers]) } end c.include RSpec::Rails::ModelExampleGroup, :type => :model, :example_group => { :file_path => c.escaped_path(%w[spec models]) } c.include RSpec::Rails::RequestExampleGroup, :type => :request, :example_group => { :file_path => c.escaped_path(%w[spec (requests|integration|api)]) } c.include RSpec::Rails::RoutingExampleGroup, :type => :routing, :example_group => { :file_path => c.escaped_path(%w[spec routing]) } c.include RSpec::Rails::ViewExampleGroup, :type => :view, :example_group => { :file_path => c.escaped_path(%w[spec views]) } c.include RSpec::Rails::FeatureExampleGroup, :type => :feature, :example_group => { :file_path => c.escaped_path(%w[spec features]) } end rspec-rails-2.13.2/lib/rspec/rails/example/000077500000000000000000000000001214604200000204375ustar00rootroot00000000000000rspec-rails-2.13.2/lib/rspec/rails/example/controller_example_group.rb000066400000000000000000000122041214604200000260750ustar00rootroot00000000000000RSpec.configure do |config| config.add_setting :infer_base_class_for_anonymous_controllers, :default => false end module RSpec::Rails module ControllerExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup include ActionController::TestCase::Behavior include RSpec::Rails::ViewRendering include RSpec::Rails::Matchers::RedirectTo include RSpec::Rails::Matchers::RenderTemplate include RSpec::Rails::Matchers::RoutingMatchers include RSpec::Rails::AssertionDelegator.new(ActionDispatch::Assertions::RoutingAssertions) module ClassMethods # @private def controller_class described_class end # Supports a simple DSL for specifying behavior of ApplicationController. # Creates an anonymous subclass of ApplicationController and evals the # `body` in that context. Also sets up implicit routes for this # controller, that are separate from those defined in "config/routes.rb". # # @note Due to Ruby 1.8 scoping rules in anoymous subclasses, constants # defined in `ApplicationController` must be fully qualified (e.g. # `ApplicationController::AccessDenied`) in the block passed to the # `controller` method. Any instance methods, filters, etc, that are # defined in `ApplicationController`, however, are accessible from # within the block. # # @example # # describe ApplicationController do # controller do # def index # raise ApplicationController::AccessDenied # end # end # # describe "handling AccessDenied exceptions" do # it "redirects to the /401.html page" do # get :index # response.should redirect_to("/401.html") # end # end # end # # If you would like to spec a subclass of ApplicationController, call # controller like so: # # controller(ApplicationControllerSubclass) do # # .... # end def controller(base_class = nil, &body) base_class ||= RSpec.configuration.infer_base_class_for_anonymous_controllers? ? controller_class : ApplicationController metadata[:example_group][:described_class] = Class.new(base_class) do def self.name; "AnonymousController"; end end metadata[:example_group][:described_class].class_eval(&body) before do @orig_routes = self.routes self.routes = ActionDispatch::Routing::RouteSet.new.tap { |r| r.draw { resources :anonymous } } end after do self.routes = @orig_routes @orig_routes = nil end end # Specifies the routeset that will be used for the example group. This # is most useful when testing Rails engines. # # @example # # describe MyEngine::PostsController do # routes { MyEngine::Engine.routes } # # # ... # end def routes(&blk) before do self.routes = blk.call end end end attr_reader :controller, :routes # @api private def routes=(routes) @routes = routes assertion_instance.instance_variable_set(:@routes, routes) end module BypassRescue def rescue_with_handler(exception) raise exception end end # Extends the controller with a module that overrides # `rescue_with_handler` to raise the exception passed to it. Use this to # specify that an action _should_ raise an exception given appropriate # conditions. # # @example # # describe ProfilesController do # it "raises a 403 when a non-admin user tries to view another user's profile" do # profile = create_profile # login_as profile.user # # expect do # bypass_rescue # get :show, :id => profile.id + 1 # end.to raise_error(/403 Forbidden/) # end # end def bypass_rescue controller.extend(BypassRescue) end # If method is a named_route, delegates to the RouteSet associated with # this controller. def method_missing(method, *args, &block) if @routes && @routes.named_routes.helpers.include?(method) controller.send(method, *args, &block) elsif @orig_routes && @orig_routes.named_routes.helpers.include?(method) controller.send(method, *args, &block) else super end end def subject controller end included do metadata[:type] = :controller before do self.routes = ::Rails.application.routes end around do |ex| previous_allow_forgery_protection_value = ActionController::Base.allow_forgery_protection begin ActionController::Base.allow_forgery_protection = false ex.call ensure ActionController::Base.allow_forgery_protection = previous_allow_forgery_protection_value end end end end end rspec-rails-2.13.2/lib/rspec/rails/example/feature_example_group.rb000066400000000000000000000014431214604200000253500ustar00rootroot00000000000000module RSpec::Rails module FeatureExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup DEFAULT_HOST = "www.example.com" included do metadata[:type] = :feature app = ::Rails.application if app.respond_to?(:routes) include app.routes.url_helpers if app.routes.respond_to?(:url_helpers) include app.routes.mounted_helpers if app.routes.respond_to?(:mounted_helpers) if respond_to?(:default_url_options) default_url_options[:host] ||= ::RSpec::Rails::FeatureExampleGroup::DEFAULT_HOST end end end def visit(*) if defined?(super) super else raise "Capybara not loaded, please add it to your Gemfile:\n\ngem \"capybara\"" end end end end rspec-rails-2.13.2/lib/rspec/rails/example/helper_example_group.rb000066400000000000000000000016631214604200000252000ustar00rootroot00000000000000require 'rspec/rails/view_assigns' module RSpec::Rails module HelperExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup include ActionView::TestCase::Behavior include RSpec::Rails::ViewAssigns module ClassMethods # @api private def determine_default_helper_class(ignore) described_class end end # Returns an instance of ActionView::Base with the helper being specified # mixed in, along with any of the built-in rails helpers. def helper _view.tap do |v| v.extend(ApplicationHelper) if defined?(ApplicationHelper) v.assign(view_assigns) end end private def _controller_path example.example_group.described_class.to_s.sub(/Helper/,'').underscore end included do metadata[:type] = :helper before do controller.controller_path = _controller_path end end end end rspec-rails-2.13.2/lib/rspec/rails/example/mailer_example_group.rb000066400000000000000000000011271214604200000251650ustar00rootroot00000000000000if defined?(ActionMailer) module RSpec::Rails module MailerExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup include ActionMailer::TestCase::Behavior included do metadata[:type] = :mailer include ::Rails.application.routes.url_helpers options = ::Rails.configuration.action_mailer.default_url_options options.each { |key, value| default_url_options[key] = value } if options end module ClassMethods def mailer_class described_class end end end end end rspec-rails-2.13.2/lib/rspec/rails/example/model_example_group.rb000066400000000000000000000002771214604200000250210ustar00rootroot00000000000000module RSpec::Rails module ModelExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup included do metadata[:type] = :model end end end rspec-rails-2.13.2/lib/rspec/rails/example/rails_example_group.rb000066400000000000000000000007321214604200000250270ustar00rootroot00000000000000# Temporary workaround to resolve circular dependency between rspec-rails' spec # suite and ammeter. require 'rspec/rails/matchers' module RSpec module Rails module RailsExampleGroup extend ActiveSupport::Concern include RSpec::Rails::SetupAndTeardownAdapter include RSpec::Rails::MiniTestLifecycleAdapter if ::Rails::VERSION::STRING >= '4' include RSpec::Rails::TestUnitAssertionAdapter include RSpec::Rails::Matchers end end end rspec-rails-2.13.2/lib/rspec/rails/example/request_example_group.rb000066400000000000000000000010441214604200000254020ustar00rootroot00000000000000module RSpec::Rails module RequestExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup include ActionDispatch::Integration::Runner include ActionDispatch::Assertions include RSpec::Rails::Matchers::RedirectTo include RSpec::Rails::Matchers::RenderTemplate include ActionController::TemplateAssertions def app ::Rails.application end included do metadata[:type] = :request before do @routes = ::Rails.application.routes end end end end rspec-rails-2.13.2/lib/rspec/rails/example/routing_example_group.rb000066400000000000000000000026501214604200000254050ustar00rootroot00000000000000require "action_dispatch/testing/assertions/routing" module RSpec::Rails module RoutingExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup include RSpec::Rails::Matchers::RoutingMatchers include RSpec::Rails::Matchers::RoutingMatchers::RouteHelpers include RSpec::Rails::AssertionDelegator.new(ActionDispatch::Assertions::RoutingAssertions) module ClassMethods # Specifies the routeset that will be used for the example group. This # is most useful when testing Rails engines. # # @example # # describe MyEngine::PostsController do # routes { MyEngine::Engine.routes } # # it "routes posts#index" do # expect(:get => "/posts").to # route_to(:controller => "my_engine/posts", :action => "index") # end # end def routes(&blk) before do self.routes = blk.call end end end included do metadata[:type] = :routing before do self.routes = ::Rails.application.routes end end attr_reader :routes # @api private def routes=(routes) @routes = routes assertion_instance.instance_variable_set(:@routes, routes) end private def method_missing(m, *args, &block) routes.url_helpers.respond_to?(m) ? routes.url_helpers.send(m, *args) : super end end end rspec-rails-2.13.2/lib/rspec/rails/example/view_example_group.rb000066400000000000000000000120301214604200000246610ustar00rootroot00000000000000require 'rspec/rails/view_assigns' module RSpec::Rails module ViewExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup include ActionView::TestCase::Behavior include RSpec::Rails::ViewAssigns include RSpec::Rails::Matchers::RenderTemplate module ClassMethods def _default_helper base = metadata[:example_group][:description].split('/')[0..-2].join('/') (base.camelize + 'Helper').constantize if base rescue NameError nil end def _default_helpers helpers = [_default_helper].compact helpers << ApplicationHelper if Object.const_defined?('ApplicationHelper') helpers end end module ExampleMethods # @overload render # @overload render({:partial => path_to_file}) # @overload render({:partial => path_to_file}, {... locals ...}) # @overload render({:partial => path_to_file}, {... locals ...}) do ... end # # Delegates to ActionView::Base#render, so see documentation on that # for more info. # # The only addition is that you can call render with no arguments, and RSpec # will pass the top level description to render: # # describe "widgets/new.html.erb" do # it "shows all the widgets" do # render # => view.render(:file => "widgets/new.html.erb") # # ... # end # end def render(options={}, local_assigns={}, &block) options = _default_render_options if Hash === options and options.empty? super(options, local_assigns, &block) end # The instance of `ActionView::Base` that is used to render the template. # Use this to stub methods _before_ calling `render`. # # describe "widgets/new.html.erb" do # it "shows all the widgets" do # view.stub(:foo) { "foo" } # render # # ... # end # end def view _view end # Simulates the presence of a template on the file system by adding a # Rails' FixtureResolver to the front of the view_paths list. Designed to # help isolate view examples from partials rendered by the view template # that is the subject of the example. # # @example # # stub_template("widgets/_widget.html.erb" => "This content.") def stub_template(hash) view.view_paths.unshift(ActionView::FixtureResolver.new(hash)) end # Provides access to the params hash that will be available within the # view: # # params[:foo] = 'bar' def params controller.params end # @deprecated Use `view` instead. def template RSpec.deprecate("template","view") view end # @deprecated Use `rendered` instead. def response # `assert_template` expects `response` to implement a #body method # like an `ActionDispatch::Response` does to force the view to render. # For backwards compatibility, we use #response as an alias for # #rendered, but it needs to implement #body to avoid `assert_template` # raising a `NoMethodError`. unless rendered.respond_to?(:body) def rendered.body; self; end; end rendered end private def _default_file_to_render example.example_group.top_level_description end def _default_render_options if ::Rails::VERSION::STRING >= '3.2' # pluck the handler, format, and locale out of, eg, posts/index.de.html.haml template, *components = _default_file_to_render.split('.') handler, format, locale = *components.reverse render_options = {:template => template} render_options[:handlers] = [handler] if handler render_options[:formats] = [format] if format render_options[:locales] = [locale] if locale render_options else {:template => _default_file_to_render} end end def _path_parts _default_file_to_render.split("/") end def _controller_path _path_parts[0..-2].join("/") end def _inferred_action _path_parts.last.split(".").first end def _include_controller_helpers helpers = controller._helpers view.singleton_class.class_eval do include helpers unless included_modules.include?(helpers) end end end included do include ExampleMethods metadata[:type] = :view helper(*_default_helpers) before do _include_controller_helpers if view.lookup_context.respond_to?(:prefixes) # rails 3.1 view.lookup_context.prefixes << _controller_path end controller.controller_path = _controller_path controller.request.path_parameters[:controller] = _controller_path controller.request.path_parameters[:action] = _inferred_action unless _inferred_action =~ /^_/ end end end end rspec-rails-2.13.2/lib/rspec/rails/extensions.rb000066400000000000000000000001511214604200000215250ustar00rootroot00000000000000require 'rspec/rails/extensions/active_record/base' require 'rspec/rails/extensions/active_record/proxy' rspec-rails-2.13.2/lib/rspec/rails/extensions/000077500000000000000000000000001214604200000212035ustar00rootroot00000000000000rspec-rails-2.13.2/lib/rspec/rails/extensions/active_record/000077500000000000000000000000001214604200000240145ustar00rootroot00000000000000rspec-rails-2.13.2/lib/rspec/rails/extensions/active_record/base.rb000066400000000000000000000027531214604200000252620ustar00rootroot00000000000000module RSpec module Rails if defined?(ActiveRecord) module Extensions module ActiveRecord # Extension to enhance `should have` on AR Model classes # # @example # # ModelClass.should have(:no).records # ModelClass.should have(1).record # ModelClass.should have(n).records def records find(:all) end alias :record :records end class ::ActiveRecord::Base extend RSpec::Rails::Extensions::ActiveRecord end end end end end if defined?(::ActiveModel) module ::ActiveModel::Validations # Extension to enhance `should have` on AR Model instances. Calls # model.valid? in order to prepare the object's errors object. Accepts # a :context option to specify the validation context. # # You can also use this to specify the content of the error messages. # # @example # # model.should have(:no).errors_on(:attribute) # model.should have(1).error_on(:attribute) # model.should have(n).errors_on(:attribute) # model.should have(n).errors_on(:attribute, :context => :create) # # model.errors_on(:attribute).should include("can't be blank") def errors_on(attribute, options = {}) valid_args = [options[:context]].compact self.valid?(*valid_args) [self.errors[attribute]].flatten.compact end alias :error_on :errors_on end end rspec-rails-2.13.2/lib/rspec/rails/extensions/active_record/proxy.rb000066400000000000000000000012161214604200000255220ustar00rootroot00000000000000RSpec.configure do |rspec| # Delay this in order to give users a chance to configure `expect_with`... rspec.before(:suite) do if defined?(RSpec::Matchers) && RSpec::Matchers.configuration.syntax.include?(:should) && defined?(ActiveRecord::Associations) # In Rails 3.0, it was AssociationProxy. # In 3.1+, it's CollectionProxy. const_name = [:CollectionProxy, :AssociationProxy].find do |const| ActiveRecord::Associations.const_defined?(const) end proxy_class = ActiveRecord::Associations.const_get(const_name) RSpec::Matchers.configuration.add_should_and_should_not_to proxy_class end end end rspec-rails-2.13.2/lib/rspec/rails/fixture_support.rb000066400000000000000000000031361214604200000226160ustar00rootroot00000000000000module RSpec module Rails if defined?(ActiveRecord::TestFixtures) module FixtureSupport extend ActiveSupport::Concern include RSpec::Rails::SetupAndTeardownAdapter include RSpec::Rails::MiniTestLifecycleAdapter if ::Rails::VERSION::STRING > '4' include RSpec::Rails::TestUnitAssertionAdapter include ActiveRecord::TestFixtures included do # TODO (DC 2011-06-25) this is necessary because fixture_file_upload # accesses fixture_path directly on ActiveSupport::TestCase. This is # fixed in rails by https://github.com/rails/rails/pull/1861, which # should be part of the 3.1 release, at which point we can include # these lines for rails < 3.1. ActiveSupport::TestCase.class_eval do include ActiveRecord::TestFixtures self.fixture_path = RSpec.configuration.fixture_path end # /TODO self.fixture_path = RSpec.configuration.fixture_path self.use_transactional_fixtures = RSpec.configuration.use_transactional_fixtures self.use_instantiated_fixtures = RSpec.configuration.use_instantiated_fixtures fixtures RSpec.configuration.global_fixtures if RSpec.configuration.global_fixtures end end RSpec.configure do |c| c.include RSpec::Rails::FixtureSupport c.add_setting :use_transactional_fixtures, :alias_with => :use_transactional_examples c.add_setting :use_instantiated_fixtures c.add_setting :global_fixtures c.add_setting :fixture_path end end end end rspec-rails-2.13.2/lib/rspec/rails/matchers.rb000066400000000000000000000012051214604200000211350ustar00rootroot00000000000000require 'rspec/core/deprecation' require 'rspec/expectations' module RSpec::Rails module Matchers end end begin require 'test/unit/assertionfailederror' rescue LoadError module Test module Unit class AssertionFailedError < StandardError end end end end require 'rspec/rails/matchers/have_rendered' require 'rspec/rails/matchers/redirect_to' require 'rspec/rails/matchers/routing_matchers' require 'rspec/rails/matchers/be_new_record' require 'rspec/rails/matchers/be_a_new' require 'rspec/rails/matchers/have_extension' require 'rspec/rails/matchers/relation_match_array' require 'rspec/rails/matchers/be_valid' rspec-rails-2.13.2/lib/rspec/rails/matchers/000077500000000000000000000000001214604200000206125ustar00rootroot00000000000000rspec-rails-2.13.2/lib/rspec/rails/matchers/be_a_new.rb000066400000000000000000000041531214604200000227010ustar00rootroot00000000000000module RSpec::Rails::Matchers class BeANew < RSpec::Matchers::BuiltIn::BaseMatcher def initialize(expected) @expected = expected end # @api private def matches?(actual) @actual = actual actual.is_a?(expected) && actual.new_record? && attributes_match?(actual) end # Use this to specify the specific attributes to match on the new record. # # @example # # it "assigns a new Thing with the submitted attributes" do # post :create, :thing => { :name => "Illegal Value" } # assigns(:thing).should be_a_new(Thing).with(:name => nil) # end def with(expected_attributes) attributes.merge!(expected_attributes) self end # @api private def failure_message_for_should [].tap do |message| unless actual.is_a?(expected) && actual.new_record? message << "expected #{actual.inspect} to be a new #{expected.inspect}" end unless attributes_match?(actual) if unmatched_attributes.size > 1 message << "attributes #{unmatched_attributes.inspect} were not set on #{actual.inspect}" else message << "attribute #{unmatched_attributes.inspect} was not set on #{actual.inspect}" end end end.join(' and ') end private def attributes @attributes ||= {} end def attributes_match?(actual) attributes.stringify_keys.all? do |key, value| actual.attributes[key].eql?(value) end end def unmatched_attributes attributes.stringify_keys.reject do |key, value| actual.attributes[key].eql?(value) end end end # Passes if actual is an instance of `model_class` and returns `false` for # `persisted?`. Typically used to specify instance variables assigned to # views by controller actions # # @example # # get :new # assigns(:thing).should be_a_new(Thing) # # post :create, :thing => { :name => "Illegal Value" } # assigns(:thing).should be_a_new(Thing).with(:name => nil) def be_a_new(model_class) BeANew.new(model_class) end end rspec-rails-2.13.2/lib/rspec/rails/matchers/be_new_record.rb000066400000000000000000000011331214604200000237320ustar00rootroot00000000000000module RSpec::Rails::Matchers class BeANewRecord < RSpec::Matchers::BuiltIn::BaseMatcher # @api private def matches?(actual) !actual.persisted? end def failure_message_for_should "expected #{actual.inspect} to be a new record, but was persisted" end def failure_message_for_should_not "expected #{actual.inspect} to be persisted, but was a new record" end end # Passes if actual returns `false` for `persisted?`. # # @example # # get :new # assigns(:thing).should be_new_record def be_new_record BeANewRecord.new end end rspec-rails-2.13.2/lib/rspec/rails/matchers/be_valid.rb000066400000000000000000000017201214604200000227040ustar00rootroot00000000000000module RSpec::Rails::Matchers class BeValid < RSpec::Matchers::BuiltIn::Be def initialize(*args) @args = args end # @api private def matches?(actual) @actual = actual actual.valid?(*@args) end # @api private def failure_message_for_should message = "expected #{actual.inspect} to be valid" if actual.respond_to?(:errors) message << ", but got errors: #{actual.errors.full_messages.join(', ')}" end message end # @api private def failure_message_for_should_not "expected #{actual.inspect} not to be valid" end end # Passes if the given model instance's `valid?` method is true, meaning all # of the `ActiveModel::Validations` passed and no errors exist. If a message # is not given, a default message is shown listing each error. # # @example # # thing = Thing.new # thing.should be_valid def be_valid(*args) BeValid.new(*args) end end rspec-rails-2.13.2/lib/rspec/rails/matchers/have_extension.rb000066400000000000000000000025471214604200000241660ustar00rootroot00000000000000require 'active_support/core_ext/module/aliasing' require 'rspec/matchers/built_in/have' module RSpec::Rails::Matchers module HaveExtensions extend ActiveSupport::Concern # @api private # # Enhances the failure message for `should have(n)` matchers def failure_message_for_should_with_errors_on_extensions return "expected #{relativities[@relativity]}#{@expected} errors on :#{@args[0]}, got #{@actual}" if @collection_name == :errors_on return "expected #{relativities[@relativity]}#{@expected} error on :#{@args[0]}, got #{@actual}" if @collection_name == :error_on return failure_message_for_should_without_errors_on_extensions end # @api private # # Enhances the description for `should have(n)` matchers def description_with_errors_on_extensions return "have #{relativities[@relativity]}#{@expected} errors on :#{@args[0]}" if @collection_name == :errors_on return "have #{relativities[@relativity]}#{@expected} error on :#{@args[0]}" if @collection_name == :error_on return description_without_errors_on_extensions end included do alias_method_chain :failure_message_for_should, :errors_on_extensions alias_method_chain :description, :errors_on_extensions end end end RSpec::Matchers::BuiltIn::Have.class_eval do include RSpec::Rails::Matchers::HaveExtensions end rspec-rails-2.13.2/lib/rspec/rails/matchers/have_rendered.rb000066400000000000000000000017701214604200000237370ustar00rootroot00000000000000module RSpec::Rails::Matchers module RenderTemplate class RenderTemplateMatcher < RSpec::Matchers::BuiltIn::BaseMatcher def initialize(scope, expected, message=nil) @expected = Symbol === expected ? expected.to_s : expected @message = message @scope = scope end # @api private def matches?(*) match_unless_raises ActiveSupport::TestCase::Assertion do @scope.assert_template expected, @message end end # @api private def failure_message_for_should rescued_exception.message end # @api private def failure_message_for_should_not "expected not to render #{expected.inspect}, but did" end end # Delegates to `assert_template` # # @example # # response.should have_rendered("new") def have_rendered(options, message=nil) RenderTemplateMatcher.new(self, options, message) end alias_method :render_template, :have_rendered end end rspec-rails-2.13.2/lib/rspec/rails/matchers/redirect_to.rb000066400000000000000000000015241214604200000234440ustar00rootroot00000000000000module RSpec::Rails::Matchers module RedirectTo class RedirectTo < RSpec::Matchers::BuiltIn::BaseMatcher def initialize(scope, expected) @expected = expected @scope = scope end # @api private def matches?(_) match_unless_raises ActiveSupport::TestCase::Assertion do @scope.assert_redirected_to(@expected) end end # @api private def failure_message_for_should rescued_exception.message end # @api private def failure_message_for_should_not "expected not to redirect to #{@expected.inspect}, but did" end end # Delegates to `assert_redirected_to` # # @example # # response.should redirect_to(:action => "new") def redirect_to(target) RedirectTo.new(self, target) end end end rspec-rails-2.13.2/lib/rspec/rails/matchers/relation_match_array.rb000066400000000000000000000002301214604200000253210ustar00rootroot00000000000000if defined?(ActiveRecord::Relation) RSpec::Matchers::OperatorMatcher.register(ActiveRecord::Relation, '=~', RSpec::Matchers::BuiltIn::MatchArray) end rspec-rails-2.13.2/lib/rspec/rails/matchers/routing_matchers.rb000066400000000000000000000063351214604200000245230ustar00rootroot00000000000000module RSpec::Rails::Matchers module RoutingMatchers extend RSpec::Matchers::DSL class RouteToMatcher < RSpec::Matchers::BuiltIn::BaseMatcher def initialize(scope, *expected) @scope = scope @expected = expected[1] || {} if Hash === expected[0] @expected.merge!(expected[0]) else controller, action = expected[0].split('#') @expected.merge!(:controller => controller, :action => action) end end # @api private def matches?(verb_to_path_map) @actual = @verb_to_path_map = verb_to_path_map # assert_recognizes does not consider ActionController::RoutingError an # assertion failure, so we have to capture that and Assertion here. match_unless_raises ActiveSupport::TestCase::Assertion, ActionController::RoutingError do path, query = *verb_to_path_map.values.first.split('?') @scope.assert_recognizes( @expected, {:method => verb_to_path_map.keys.first, :path => path}, Rack::Utils::parse_query(query) ) end end # @api private def failure_message_for_should rescued_exception.message end def description "route #{@actual.inspect} to #{@expected.inspect}" end end # Delegates to `assert_recognizes`. Supports short-hand controller/action # declarations (e.g. `"controller#action"`). # # @example # # { :get => "/things/special" }.should route_to( # :controller => "things", # :action => "special" # ) # # { :get => "/things/special" }.should route_to("things#special") # # @see http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-assert_recognizes def route_to(*expected) RouteToMatcher.new(self, *expected) end class BeRoutableMatcher < RSpec::Matchers::BuiltIn::BaseMatcher def initialize(scope) @scope = scope end # @api private def matches?(path) @actual = path match_unless_raises ActionController::RoutingError do @routing_options = @scope.routes.recognize_path( path.values.first, :method => path.keys.first ) end end def failure_message_for_should "expected #{@actual.inspect} to be routable" end def failure_message_for_should_not "expected #{@actual.inspect} not to be routable, but it routes to #{@routing_options.inspect}" end end # Passes if the route expression is recognized by the Rails router based on # the declarations in `config/routes.rb`. Delegates to # `RouteSet#recognize_path`. # # @example # # You can use route helpers provided by rspec-rails. # {:get => "/a/path"}.should be_routable # {:post => "/another/path"}.should be_routable # {:put => "/yet/another/path"}.should_not be_routable def be_routable BeRoutableMatcher.new(self) end module RouteHelpers %w(get post put patch delete options head).each do |method| define_method method do |path| { method.to_sym => path } end end end end end rspec-rails-2.13.2/lib/rspec/rails/mocks.rb000066400000000000000000000210611214604200000204450ustar00rootroot00000000000000require 'active_support/core_ext' require 'active_model' module RSpec module Rails class IllegalDataAccessException < StandardError; end module Mocks module ActiveModelInstanceMethods # Stubs `persisted?` to return false and `id` to return nil # @return self def as_new_record self.stub(:persisted?) { false } self.stub(:id) { nil } self end # Returns true by default. Override with a stub. def persisted? true end # Returns false for names matching /_before_type_cast$/, # otherwise delegates to super. def respond_to?(message, include_private=false) message.to_s =~ /_before_type_cast$/ ? false : super end end module ActiveRecordInstanceMethods # Stubs `persisted?` to return `false` and `id` to return `nil`. def destroy self.stub(:persisted?) { false } self.stub(:id) { nil } end # Transforms the key to a method and calls it. def [](key) send(key) end # Returns the opposite of `persisted?` def new_record? !persisted? end end # Creates a test double representing `string_or_model_class` with common # ActiveModel methods stubbed out. Additional methods may be easily # stubbed (via add_stubs) if `stubs` is passed. This is most useful for # impersonating models that don't exist yet. # # NOTE that only ActiveModel's methods, plus new_record?, are # stubbed out implicitly. new_record? returns the inverse of # persisted?, and is present only for compatibility with # extension frameworks that have yet to update themselves to the # ActiveModel API (which declares persisted?, not # new_record?). # # `string_or_model_class` can be any of: # # * A String representing a Class that does not exist # * A String representing a Class that extends ActiveModel::Naming # * A Class that extends ActiveModel::Naming def mock_model(string_or_model_class, stubs = {}) if String === string_or_model_class if Object.const_defined?(string_or_model_class) model_class = Object.const_get(string_or_model_class) else model_class = Object.const_set(string_or_model_class, Class.new do extend ActiveModel::Naming def self.primary_key; :id; end end) end else model_class = string_or_model_class end unless model_class.kind_of? ActiveModel::Naming raise ArgumentError.new <<-EOM The mock_model method can only accept as its first argument: * A String representing a Class that does not exist * A String representing a Class that extends ActiveModel::Naming * A Class that extends ActiveModel::Naming It received #{model_class.inspect} EOM end stubs = stubs.reverse_merge(:id => next_id) stubs = stubs.reverse_merge(:persisted? => !!stubs[:id], :destroyed? => false, :marked_for_destruction? => false, :valid? => true, :blank? => false) double("#{model_class.name}_#{stubs[:id]}", stubs).tap do |m| m.singleton_class.class_eval do include ActiveModelInstanceMethods include ActiveRecordInstanceMethods if defined?(ActiveRecord) include ActiveModel::Conversion include ActiveModel::Validations end if defined?(ActiveRecord) [:save, :update_attributes, :update].each do |key| if stubs[key] == false m.errors.stub(:empty? => false) end end end m.__send__(:__mock_proxy).instance_eval(<<-CODE, __FILE__, __LINE__) def @object.is_a?(other) #{model_class}.ancestors.include?(other) end unless #{stubs.has_key?(:is_a?)} def @object.kind_of?(other) #{model_class}.ancestors.include?(other) end unless #{stubs.has_key?(:kind_of?)} def @object.instance_of?(other) other == #{model_class} end unless #{stubs.has_key?(:instance_of?)} def @object.__model_class_has_column?(method_name) #{model_class}.respond_to?(:column_names) && #{model_class}.column_names.include?(method_name.to_s) end def @object.respond_to?(method_name, include_private=false) __model_class_has_column?(method_name) ? true : super end unless #{stubs.has_key?(:respond_to?)} def @object.method_missing(m, *a, &b) respond_to?(m) ? null_object? ? self : nil : super end def @object.class #{model_class} end unless #{stubs.has_key?(:class)} def @object.to_s "#{model_class.name}_#{to_param}" end unless #{stubs.has_key?(:to_s)} CODE yield m if block_given? end end module ActiveModelStubExtensions # Stubs `persisted` to return false and `id` to return nil def as_new_record self.stub(:persisted?) { false } self.stub(:id) { nil } self end # Returns `true` by default. Override with a stub. def persisted? true end end module ActiveRecordStubExtensions # Stubs `id` (or other primary key method) to return nil def as_new_record self.__send__("#{self.class.primary_key}=", nil) super end # Returns the opposite of `persisted?`. def new_record? !persisted? end # Raises an IllegalDataAccessException (stubbed models are not allowed to access the database) # @raises IllegalDataAccessException def connection raise RSpec::Rails::IllegalDataAccessException.new("stubbed models are not allowed to access the database") end end # Creates an instance of `Model` with `to_param` stubbed using a # generated value that is unique to each object. If `Model` is an # `ActiveRecord` model, it is prohibited from accessing the database*. # # For each key in `stubs`, if the model has a matching attribute # (determined by `respond_to?`) it is simply assigned the submitted values. # If the model does not have a matching attribute, the key/value pair is # assigned as a stub return value using RSpec's mocking/stubbing # framework. # # persisted? is overridden to return the result of !id.nil? # This means that by default persisted? will return true. If you want # the object to behave as a new record, sending it `as_new_record` will # set the id to nil. You can also explicitly set :id => nil, in which # case persisted? will return false, but using `as_new_record` makes the # example a bit more descriptive. # # While you can use stub_model in any example (model, view, controller, # helper), it is especially useful in view examples, which are # inherently more state-based than interaction-based. # # @example # # stub_model(Person) # stub_model(Person).as_new_record # stub_model(Person, :to_param => 37) # stub_model(Person) {|person| person.first_name = "David"} def stub_model(model_class, stubs={}) model_class.new.tap do |m| m.extend ActiveModelStubExtensions if defined?(ActiveRecord) && model_class < ActiveRecord::Base m.extend ActiveRecordStubExtensions primary_key = model_class.primary_key.to_sym stubs = stubs.reverse_merge(primary_key => next_id) stubs = stubs.reverse_merge(:persisted? => !!stubs[primary_key]) else stubs = stubs.reverse_merge(:id => next_id) stubs = stubs.reverse_merge(:persisted? => !!stubs[:id]) end stubs = stubs.reverse_merge(:blank? => false) stubs.each do |k,v| m.__send__("#{k}=", stubs.delete(k)) if m.respond_to?("#{k}=") end m.stub(stubs) yield m if block_given? end end private @@model_id = 1000 def next_id @@model_id += 1 end end end end RSpec.configuration.include RSpec::Rails::Mocks rspec-rails-2.13.2/lib/rspec/rails/module_inclusion.rb000066400000000000000000000014411214604200000227010ustar00rootroot00000000000000module RSpec::Rails module ModuleInclusion # @deprecated No replacement. # # Will be removed from rspec-rails-3.0 # # This was never intended to be a public API and is no longer needed # internally. As it happens, there are a few blog posts citing its use, so # I'm leaving it here, but deprecated. def include_self_when_dir_matches(*path_parts) instead = <<-INSTEAD RSpec.configure do |c| c.include self, :example_group => { :file_path => /#{path_parts.join('\/')}/ } end INSTEAD lambda do |c| RSpec.deprecate('include_self_when_dir_matches', instead, 'rails-3.0') c.include self, :example_group => { :file_path => Regexp.compile(path_parts.join('[\\\/]')) } end end end end rspec-rails-2.13.2/lib/rspec/rails/tasks/000077500000000000000000000000001214604200000201315ustar00rootroot00000000000000rspec-rails-2.13.2/lib/rspec/rails/tasks/rspec.rake000066400000000000000000000026031214604200000221120ustar00rootroot00000000000000require 'rspec/core/rake_task' if default = Rake.application.instance_variable_get('@tasks')['default'] default.prerequisites.delete('test') end spec_prereq = Rails.configuration.generators.options[:rails][:orm] == :active_record ? "test:prepare" : :noop task :noop do; end task :default => :spec task :stats => "spec:statsetup" desc "Run all specs in spec directory (excluding plugin specs)" RSpec::Core::RakeTask.new(:spec => spec_prereq) namespace :spec do def types dirs = Dir['./spec/**/*_spec.rb'].map { |f| f.sub(/^\.\/(spec\/\w+)\/.*/, '\\1') }.uniq Hash[dirs.map { |d| [d.split('/').last, d] }] end types.each do |type, dir| desc "Run the code examples in #{dir}" RSpec::Core::RakeTask.new(type => spec_prereq) do |t| t.pattern = "./#{dir}/**/*_spec.rb" end end # RCov task only enabled for Ruby 1.8 if RUBY_VERSION < '1.9' desc "Run all specs with rcov" RSpec::Core::RakeTask.new(:rcov => spec_prereq) do |t| t.rcov = true t.pattern = "./spec/**/*_spec.rb" t.rcov_opts = '--exclude /gems/,/Library/,/usr/,lib/tasks,.bundle,config,/lib/rspec/,/lib/rspec-,spec' end end task :statsetup do require 'rails/code_statistics' types.each do |type, dir| name = type.singularize.capitalize ::STATS_DIRECTORIES << ["#{name} specs", dir] ::CodeStatistics::TEST_TYPES << "#{name} specs" end end end rspec-rails-2.13.2/lib/rspec/rails/vendor/000077500000000000000000000000001214604200000203015ustar00rootroot00000000000000rspec-rails-2.13.2/lib/rspec/rails/vendor/capybara.rb000066400000000000000000000015701214604200000224130ustar00rootroot00000000000000begin require 'capybara/rspec' rescue LoadError end begin require 'capybara/rails' rescue LoadError end if defined?(Capybara) RSpec.configure do |c| if defined?(Capybara::DSL) c.include Capybara::DSL, :type => :controller c.include Capybara::DSL, :type => :feature end if defined?(Capybara::RSpecMatchers) c.include Capybara::RSpecMatchers, :type => :view c.include Capybara::RSpecMatchers, :type => :helper c.include Capybara::RSpecMatchers, :type => :mailer c.include Capybara::RSpecMatchers, :type => :controller c.include Capybara::RSpecMatchers, :example_group => { :file_path => c.escaped_path(%w[spec features]) } end unless defined?(Capybara::RSpecMatchers) || defined?(Capybara::DSL) c.include Capybara, :type => :request c.include Capybara, :type => :controller end end end rspec-rails-2.13.2/lib/rspec/rails/vendor/webrat.rb000066400000000000000000000014201214604200000221070ustar00rootroot00000000000000begin require 'webrat' rescue LoadError end RSpec.configure do |c| if defined?(Webrat) c.include Webrat::Matchers, :type => :request c.include Webrat::Matchers, :type => :controller c.include Webrat::Matchers, :type => :view c.include Webrat::Matchers, :type => :helper c.include Webrat::Matchers, :type => :mailer c.include Webrat::Methods, :type => :request c.include Webrat::Methods, :type => :controller module RequestInstanceMethods def last_response @response end end c.include RequestInstanceMethods, :type => :request c.before :type => :controller do Webrat.configure {|w| w.mode = :rails} end c.before :type => :request do Webrat.configure {|w| w.mode = :rack} end end end rspec-rails-2.13.2/lib/rspec/rails/version.rb000066400000000000000000000001311214604200000210110ustar00rootroot00000000000000module RSpec module Rails module Version STRING = '2.13.2' end end end rspec-rails-2.13.2/lib/rspec/rails/view_assigns.rb000066400000000000000000000024601214604200000220340ustar00rootroot00000000000000module RSpec module Rails module ViewAssigns # Assigns a value to an instance variable in the scope of the # view being rendered. # # @example # # assign(:widget, stub_model(Widget)) def assign(key, value) _encapsulated_assigns[key] = value end def view_assigns begin # TODO: _assigns was deprecated in favor of view_assigns after # Rails-3.0.0 was released. Since we are not able to predict when # the _assigns/view_assigns patch will be released (I thought it # would have been in 3.0.1, but 3.0.1 bypassed this change for a # security fix), this bit ensures that we do the right thing without # knowing anything about the Rails version we are dealing with. # # Once that change _is_ released, this can be changed to something # that checks for the Rails version when the module is being # interpreted, as it was before commit dd0095. super.merge(_encapsulated_assigns) rescue _assigns end end # @api private def _assigns super.merge(_encapsulated_assigns) end private def _encapsulated_assigns @_encapsulated_assigns ||= {} end end end end rspec-rails-2.13.2/lib/rspec/rails/view_rendering.rb000066400000000000000000000067711214604200000223530ustar00rootroot00000000000000require 'action_view/testing/resolvers' RSpec.configure do |config| # This allows us to expose `render_views` as a config option even though it # breaks the convention of other options by using `render_views` as a # command (i.e. render_views = true), where it would normally be used as a # getter. This makes it easier for rspec-rails users because we use # `render_views` directly in example groups, so this aligns the two APIs, # but requires this workaround: config.add_setting :rendering_views, :default => false def config.render_views=(val) self.rendering_views = val end def config.render_views self.rendering_views = true end def config.render_views? rendering_views end end module RSpec module Rails module ViewRendering extend ActiveSupport::Concern attr_accessor :controller module ClassMethods def metadata_for_rspec_rails metadata[:rspec_rails] = metadata[:rspec_rails] ? metadata[:rspec_rails].dup : {} end # @see RSpec::Rails::ControllerExampleGroup def render_views(true_or_false=true) metadata_for_rspec_rails[:render_views] = true_or_false end # @deprecated Use `render_views` instead. def integrate_views RSpec.deprecate("integrate_views","render_views") render_views end # @api private def render_views? metadata_for_rspec_rails.fetch(:render_views) do RSpec.configuration.render_views? end end end # @api private def render_views? self.class.render_views? || !controller.class.respond_to?(:view_paths) end # Delegates find_all to the submitted path set and then returns templates # with modified source class EmptyTemplatePathSetDecorator < ::ActionView::Resolver attr_reader :original_path_set def initialize(original_path_set) @original_path_set = original_path_set end # @api private def find_all(*args) original_path_set.find_all(*args).collect do |template| ::ActionView::Template.new( "", template.identifier, EmptyTemplateHandler, { :virtual_path => template.virtual_path, :format => template.formats } ) end end end class EmptyTemplateHandler def self.call(template) %("") end end module EmptyTemplates # @api private def prepend_view_path(new_path) lookup_context.view_paths.unshift(*_path_decorator(new_path)) end # @api private def append_view_path(new_path) lookup_context.view_paths.push(*_path_decorator(new_path)) end private def _path_decorator(path) EmptyTemplatePathSetDecorator.new(ActionView::PathSet.new(Array.wrap(path))) end end included do before do unless render_views? @_empty_view_path_set_delegator = EmptyTemplatePathSetDecorator.new(controller.class.view_paths) controller.class.view_paths = ::ActionView::PathSet.new.push(@_empty_view_path_set_delegator) controller.extend(EmptyTemplates) end end after do unless render_views? controller.class.view_paths = @_empty_view_path_set_delegator.original_path_set end end end end end end rspec-rails-2.13.2/rspec-rails.gemspec000066400000000000000000000032451214604200000176050ustar00rootroot00000000000000# -*- encoding: utf-8 -*- $LOAD_PATH.unshift File.expand_path("../lib", __FILE__) require "rspec/rails/version" Gem::Specification.new do |s| s.name = "rspec-rails" s.version = RSpec::Rails::Version::STRING s.platform = Gem::Platform::RUBY s.license = "MIT" s.authors = ["David Chelimsky"] s.email = "rspec-users@rubyforge.org" s.homepage = "http://github.com/rspec/rspec-rails" s.summary = "rspec-rails-#{RSpec::Rails::Version::STRING}" s.description = "RSpec for Rails" s.rubyforge_project = "rspec" s.files = `git ls-files -- lib/*`.split("\n") s.files += %w[README.md License.txt Changelog.md Capybara.md .yardopts .document] s.test_files = `git ls-files -- {spec,features}/*`.split("\n") s.rdoc_options = ["--charset=UTF-8"] s.require_path = "lib" s.add_runtime_dependency(%q, [">= 3.0"]) s.add_runtime_dependency(%q, [">= 3.0"]) s.add_runtime_dependency(%q, [">= 3.0"]) %w[core expectations mocks].each do |name| if RSpec::Rails::Version::STRING =~ /[a-zA-Z]+/ # prerelease builds s.add_runtime_dependency "rspec-#{name}", "= #{RSpec::Rails::Version::STRING}" else s.add_runtime_dependency "rspec-#{name}", "~> #{RSpec::Rails::Version::STRING.split('.')[0..1].concat(['0']).join('.')}" end end s.add_development_dependency 'rake', '~> 10.0.0' s.add_development_dependency 'cucumber', '~> 1.1.9' s.add_development_dependency 'aruba', '~> 0.4.11' s.add_development_dependency 'ZenTest', '4.9.0' s.add_development_dependency 'ammeter', '0.2.5' s.add_development_dependency 'capybara', '>= 2.0.0' end rspec-rails-2.13.2/script/000077500000000000000000000000001214604200000153145ustar00rootroot00000000000000rspec-rails-2.13.2/script/download-ruby-debug-19-dependencies000077500000000000000000000002751214604200000237730ustar00rootroot00000000000000mkdir -p vendor/cache cd vendor/cache wget http://rubyforge.org/frs/download.php/75414/linecache19-0.5.13.gem wget http://rubyforge.org/frs/download.php/75415/ruby-debug-base19-0.11.26.gem rspec-rails-2.13.2/spec/000077500000000000000000000000001214604200000147425ustar00rootroot00000000000000rspec-rails-2.13.2/spec/autotest/000077500000000000000000000000001214604200000166125ustar00rootroot00000000000000rspec-rails-2.13.2/spec/autotest/rails_rspec2_spec.rb000066400000000000000000000020161214604200000225400ustar00rootroot00000000000000require "spec_helper" require "autotest/rails_rspec2" describe Autotest::RailsRspec2 do let(:rails_rspec2_autotest) { Autotest::RailsRspec2.new } describe 'exceptions' do let(:exceptions_regexp) { rails_rspec2_autotest.exceptions } it "matches './log/test.log'" do exceptions_regexp.should match('./log/test.log') end it "matches 'log/test.log'" do exceptions_regexp.should match('log/test.log') end it "does not match './spec/models/user_spec.rb'" do exceptions_regexp.should_not match('./spec/models/user_spec.rb') end it "does not match 'spec/models/user_spec.rb'" do exceptions_regexp.should_not match('spec/models/user_spec.rb') end end describe 'mappings' do it 'runs model specs when support files change' do rails_rspec2_autotest.find_order = %w(spec/models/user_spec.rb spec/support/blueprints.rb) rails_rspec2_autotest.test_files_for('spec/support/blueprints.rb').should( include('spec/models/user_spec.rb')) end end end rspec-rails-2.13.2/spec/generators/000077500000000000000000000000001214604200000171135ustar00rootroot00000000000000rspec-rails-2.13.2/spec/generators/rspec/000077500000000000000000000000001214604200000202275ustar00rootroot00000000000000rspec-rails-2.13.2/spec/generators/rspec/controller/000077500000000000000000000000001214604200000224125ustar00rootroot00000000000000rspec-rails-2.13.2/spec/generators/rspec/controller/controller_generator_spec.rb000066400000000000000000000056461214604200000302150ustar00rootroot00000000000000require 'spec_helper' # Generators are not automatically loaded by Rails require 'generators/rspec/controller/controller_generator' describe Rspec::Generators::ControllerGenerator do # Tell the generator where to put its output (what it thinks of as Rails.root) destination File.expand_path("../../../../../tmp", __FILE__) before { prepare_destination } describe 'controller specs' do subject { file('spec/controllers/posts_controller_spec.rb') } describe 'generated by default' do before do run_generator %w(posts) end describe 'the spec' do it { should exist } it { should contain(/require 'spec_helper'/) } it { should contain(/describe PostsController/) } end end describe 'skipped with a flag' do before do run_generator %w(posts --no-controller_specs) end it { should_not exist } end end describe 'view specs' do describe 'are not generated' do describe 'with no-view-spec flag' do before do run_generator %w(posts index show --no-view-specs) end describe 'index.html.erb' do subject { file('spec/views/posts/index.html.erb_spec.rb') } it { should_not exist } end end describe 'with no actions' do before do run_generator %w(posts) end describe 'index.html.erb' do subject { file('spec/views/posts/index.html.erb_spec.rb') } it { should_not exist } end end describe 'with --no-template-engine' do before do run_generator %w(posts index --no-template-engine) end describe 'index.html.erb' do subject { file('spec/views/posts/index.html._spec.rb') } it { should_not exist } end end end describe 'are generated' do describe 'with default template engine' do before do run_generator %w(posts index show) end describe 'index.html.erb' do subject { file('spec/views/posts/index.html.erb_spec.rb') } it { should exist } it { should contain(/require 'spec_helper'/) } it { should contain(/describe "posts\/index.html.erb"/) } end describe 'show.html.erb' do subject { file('spec/views/posts/show.html.erb_spec.rb') } it { should exist } it { should contain(/require 'spec_helper'/) } it { should contain(/describe "posts\/show.html.erb"/) } end end describe 'with haml' do before do run_generator %w(posts index --template_engine haml) end describe 'index.html.haml' do subject { file('spec/views/posts/index.html.haml_spec.rb') } it { should exist } it { should contain(/require 'spec_helper'/) } it { should contain(/describe "posts\/index.html.haml"/) } end end end end end rspec-rails-2.13.2/spec/generators/rspec/helper/000077500000000000000000000000001214604200000215065ustar00rootroot00000000000000rspec-rails-2.13.2/spec/generators/rspec/helper/helper_generator_spec.rb000066400000000000000000000014561214604200000264000ustar00rootroot00000000000000require 'spec_helper' # Generators are not automatically loaded by Rails require 'generators/rspec/helper/helper_generator' describe Rspec::Generators::HelperGenerator do # Tell the generator where to put its output (what it thinks of as Rails.root) destination File.expand_path("../../../../../tmp", __FILE__) before { prepare_destination } subject { file('spec/helpers/posts_helper_spec.rb') } describe 'generated by default' do before do run_generator %w(posts) end describe 'the spec' do it { should exist } it { should contain(/require 'spec_helper'/) } it { should contain(/describe PostsHelper/) } end end describe 'skipped with a flag' do before do run_generator %w(posts --no-helper_specs) end it { should_not exist } end end rspec-rails-2.13.2/spec/generators/rspec/install/000077500000000000000000000000001214604200000216755ustar00rootroot00000000000000rspec-rails-2.13.2/spec/generators/rspec/install/install_generator_spec.rb000066400000000000000000000016411214604200000267520ustar00rootroot00000000000000require 'spec_helper' require 'generators/rspec/install/install_generator' describe Rspec::Generators::InstallGenerator do destination File.expand_path("../../../../../tmp", __FILE__) before { prepare_destination } it "generates .rspec" do run_generator file('.rspec').should exist end it "generates spec/spec_helper.rb" do run_generator File.read( file('spec/spec_helper.rb') ).should =~ /^require 'rspec\/autorun'$/m end if ::Rails::VERSION::STRING >= '4' it "generates spec/spec_helper.rb with a check for pending migrations" do run_generator File.read( file('spec/spec_helper.rb') ).should =~ /ActiveRecord::Migration\.check_pending!/m end else it "generates spec/spec_helper.rb without a check for pending migrations" do run_generator File.read( file('spec/spec_helper.rb') ).should_not =~ /ActiveRecord::Migration\.check_pending!/m end end end rspec-rails-2.13.2/spec/generators/rspec/integration/000077500000000000000000000000001214604200000225525ustar00rootroot00000000000000rspec-rails-2.13.2/spec/generators/rspec/integration/integration_generator_spec.rb000066400000000000000000000025151214604200000305050ustar00rootroot00000000000000require 'spec_helper' # Generators are not automatically loaded by Rails require 'generators/rspec/integration/integration_generator' describe Rspec::Generators::IntegrationGenerator do # Tell the generator where to put its output (what it thinks of as Rails.root) destination File.expand_path("../../../../../tmp", __FILE__) before { prepare_destination } describe 'are not generated' do before do run_generator %w(posts --no-request-specs) end describe 'index.html.erb' do subject { file('spec/requests/posts_spec.rb') } it { should_not exist } end end describe 'are generated' do describe 'without webrat matchers by default' do before do run_generator %w(posts) end subject { file('spec/requests/posts_spec.rb') } it { should exist } it { should contain(/require 'spec_helper'/) } it { should contain(/describe "GET \/posts"/) } it { should contain(/get posts_index_path/) } end describe 'with webrat matchers' do before do run_generator %w(posts --webrat) end subject { file('spec/requests/posts_spec.rb') } it { should exist } it { should contain(/require 'spec_helper'/) } it { should contain(/describe "GET \/posts"/) } it { should contain(/visit posts_index_path/) } end end end rspec-rails-2.13.2/spec/generators/rspec/mailer/000077500000000000000000000000001214604200000215005ustar00rootroot00000000000000rspec-rails-2.13.2/spec/generators/rspec/mailer/mailer_generator_spec.rb000066400000000000000000000026661214604200000263700ustar00rootroot00000000000000require 'spec_helper' # Generators are not automatically loaded by Rails require 'generators/rspec/mailer/mailer_generator' describe Rspec::Generators::MailerGenerator do # Tell the generator where to put its output (what it thinks of as Rails.root) destination File.expand_path("../../../../../tmp", __FILE__) before { prepare_destination } describe 'mailer spec' do subject { file('spec/mailers/posts_spec.rb') } describe 'a spec is created for each action' do before do run_generator %w(posts index show) end it { should exist } it { should contain(/require "spec_helper"/) } it { should contain(/describe "index" do/) } it { should contain(/describe "show" do/) } end describe 'creates placeholder when no actions specified' do before do run_generator %w(posts) end it { should exist } it { should contain(/require "spec_helper"/) } it { should contain(/pending "add some examples to \(or delete\)/) } end end describe 'a fixture is generated for each action' do before do run_generator %w(posts index show) end describe 'index' do subject { file('spec/fixtures/posts/index') } it { should exist } it { should contain(/Posts#index/) } end describe 'show' do subject { file('spec/fixtures/posts/show') } it { should exist } it { should contain(/Posts#show/) } end end end rspec-rails-2.13.2/spec/generators/rspec/model/000077500000000000000000000000001214604200000213275ustar00rootroot00000000000000rspec-rails-2.13.2/spec/generators/rspec/model/model_generator_spec.rb000066400000000000000000000025701214604200000260400ustar00rootroot00000000000000require 'spec_helper' # Generators are not automatically loaded by Rails require 'generators/rspec/model/model_generator' describe Rspec::Generators::ModelGenerator do # Tell the generator where to put its output (what it thinks of as Rails.root) destination File.expand_path("../../../../../tmp", __FILE__) before { prepare_destination } it 'runs both the model and fixture tasks' do gen = generator %w(posts) gen.should_receive :create_model_spec gen.should_receive :create_fixture_file capture(:stdout) { gen.invoke_all } end describe 'the generated files' do describe 'with fixtures' do before do run_generator %w(posts --fixture) end describe 'the spec' do subject { file('spec/models/posts_spec.rb') } it { should exist } it { should contain(/require 'spec_helper'/) } it { should contain(/describe Posts/) } end describe 'the fixtures' do subject { file('spec/fixtures/posts.yml') } it { should contain(Regexp.new('# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html')) } end end describe 'without fixtures' do before do run_generator %w(posts) end describe 'the fixtures' do subject { file('spec/fixtures/posts.yml') } it { should_not exist } end end end end rspec-rails-2.13.2/spec/generators/rspec/observer/000077500000000000000000000000001214604200000220565ustar00rootroot00000000000000rspec-rails-2.13.2/spec/generators/rspec/observer/observer_generator_spec.rb000066400000000000000000000011461214604200000273140ustar00rootroot00000000000000require 'spec_helper' # Generators are not automatically loaded by Rails require 'generators/rspec/observer/observer_generator' describe Rspec::Generators::ObserverGenerator do # Tell the generator where to put its output (what it thinks of as Rails.root) destination File.expand_path("../../../../../tmp", __FILE__) subject { file('spec/models/posts_observer_spec.rb') } before do prepare_destination run_generator %w(posts) end describe 'the spec' do it { should exist } it { should contain(/require 'spec_helper'/) } it { should contain(/describe PostsObserver/) } end end rspec-rails-2.13.2/spec/generators/rspec/scaffold/000077500000000000000000000000001214604200000220105ustar00rootroot00000000000000rspec-rails-2.13.2/spec/generators/rspec/scaffold/scaffold_generator_spec.rb000066400000000000000000000103241214604200000271760ustar00rootroot00000000000000require 'spec_helper' require 'generators/rspec/scaffold/scaffold_generator' describe Rspec::Generators::ScaffoldGenerator do destination File.expand_path("../../../../../tmp", __FILE__) before { prepare_destination } describe 'standard controller spec' do subject { file('spec/controllers/posts_controller_spec.rb') } describe 'with no options' do before { run_generator %w(posts) } it { should contain(/require 'spec_helper'/) } it { should contain(/describe PostsController/) } it { should contain(%({ "these" => "params" })) } end describe 'with --no-controller_specs' do before { run_generator %w(posts --no-controller_specs) } it { should_not exist } end end describe 'controller spec with attributes specified' do subject { file('spec/controllers/posts_controller_spec.rb') } before { run_generator %w(posts title:string) } it { should contain(%({ "title" => "MyString" })) } end describe 'namespaced controller spec' do subject { file('spec/controllers/admin/posts_controller_spec.rb') } before { run_generator %w(admin/posts) } it { should contain(/describe Admin::PostsController/)} end describe 'view specs' do describe 'with no options' do before { run_generator %w(posts) } describe 'edit' do subject { file("spec/views/posts/edit.html.erb_spec.rb") } it { should exist } it { should contain(/require 'spec_helper'/) } it { should contain(/describe "(.*)\/edit"/) } it { should contain(/it "renders the edit (.*) form"/) } end describe 'index' do subject { file("spec/views/posts/index.html.erb_spec.rb") } it { should exist } it { should contain(/require 'spec_helper'/) } it { should contain(/describe "(.*)\/index"/) } it { should contain(/it "renders a list of (.*)"/) } end describe 'new' do subject { file("spec/views/posts/new.html.erb_spec.rb") } it { should exist } it { should contain(/require 'spec_helper'/) } it { should contain(/describe "(.*)\/new"/) } it { should contain(/it "renders new (.*) form"/) } end describe 'show' do subject { file("spec/views/posts/show.html.erb_spec.rb") } it { should exist } it { should contain(/require 'spec_helper'/) } it { should contain(/describe "(.*)\/show"/) } it { should contain(/it "renders attributes in

"/) } end end describe 'with --no-template-engine' do before { run_generator %w(posts --no-template-engine) } describe 'edit' do subject { file("spec/views/posts/edit.html._spec.rb") } it { should_not exist } end describe 'index' do subject { file("spec/views/posts/index.html._spec.rb") } it { should_not exist } end describe 'new' do subject { file("spec/views/posts/new.html._spec.rb") } it { should_not exist } end describe 'show' do subject { file("spec/views/posts/show.html._spec.rb") } it { should_not exist } end end describe 'with --no-view-specs' do before { run_generator %w(posts --no-view-specs) } describe 'edit' do subject { file("spec/views/posts/edit.html.erb_spec.rb") } it { should_not exist } end describe 'index' do subject { file("spec/views/posts/index.html.erb_spec.rb") } it { should_not exist } end describe 'new' do subject { file("spec/views/posts/new.html.erb_spec.rb") } it { should_not exist } end describe 'show' do subject { file("spec/views/posts/show.html.erb_spec.rb") } it { should_not exist } end end end describe 'routing spec' do subject { file('spec/routing/posts_routing_spec.rb') } describe 'with default options' do before { run_generator %w(posts) } it { should contain(/require "spec_helper"/) } it { should contain(/describe PostsController/) } it { should contain(/describe "routing"/) } end describe 'with --no-routing-specs' do before { run_generator %w(posts --no-routing_specs) } it { should_not exist } end end end rspec-rails-2.13.2/spec/generators/rspec/view/000077500000000000000000000000001214604200000212015ustar00rootroot00000000000000rspec-rails-2.13.2/spec/generators/rspec/view/view_generator_spec.rb000066400000000000000000000025521214604200000255640ustar00rootroot00000000000000require 'spec_helper' # Generators are not automatically loaded by Rails require 'generators/rspec/view/view_generator' describe Rspec::Generators::ViewGenerator do # Tell the generator where to put its output (what it thinks of as Rails.root) destination File.expand_path("../../../../../tmp", __FILE__) before { prepare_destination } describe 'with default template engine' do it 'generates a spec for the supplied action' do run_generator %w(posts index) file('spec/views/posts/index.html.erb_spec.rb').tap do |f| f.should contain(/require 'spec_helper'/) f.should contain(/describe "posts\/index"/) end end describe 'with a nested resource' do it 'generates a spec for the supplied action' do run_generator %w(admin/posts index) file('spec/views/admin/posts/index.html.erb_spec.rb').tap do |f| f.should contain(/require 'spec_helper'/) f.should contain(/describe "admin\/posts\/index"/) end end end end describe 'with a specified template engine' do it 'generates a spec for the supplied action' do run_generator %w(posts index --template_engine haml) file('spec/views/posts/index.html.haml_spec.rb').tap do |f| f.should contain(/require 'spec_helper'/) f.should contain(/describe "posts\/index"/) end end end end rspec-rails-2.13.2/spec/rspec/000077500000000000000000000000001214604200000160565ustar00rootroot00000000000000rspec-rails-2.13.2/spec/rspec/rails/000077500000000000000000000000001214604200000171705ustar00rootroot00000000000000rspec-rails-2.13.2/spec/rspec/rails/assertion_adapter_spec.rb000066400000000000000000000014001214604200000242310ustar00rootroot00000000000000require "spec_helper" describe RSpec::Rails::TestUnitAssertionAdapter do include RSpec::Rails::TestUnitAssertionAdapter Test::Unit::Assertions.public_instance_methods.select{|m| m.to_s =~ /^(assert|flunk)/}.each do |m| if m.to_s == "assert_equal" it "exposes #{m} to host examples" do assert_equal 3,3 expect do assert_equal 3,4 end.to raise_error(ActiveSupport::TestCase::Assertion) end else it "exposes #{m} to host examples" do methods.should include(m) end end end it "does not expose internal methods of MiniTest" do methods.should_not include("_assertions") end it "does not expose MiniTest's message method" do methods.should_not include("message") end end rspec-rails-2.13.2/spec/rspec/rails/assertion_delegator_spec.rb000066400000000000000000000020121214604200000245570ustar00rootroot00000000000000require "spec_helper" describe RSpec::Rails::AssertionDelegator do it "provides a module that delegates assertion methods to an isolated class" do klass = Class.new { include RSpec::Rails::AssertionDelegator.new(Test::Unit::Assertions) } expect(klass.new).to respond_to(:assert) end it "delegates back to the including instance for methods the assertion module requires" do assertions = Module.new { def has_thing?(thing) self.things.include?(thing) end } klass = Class.new { include RSpec::Rails::AssertionDelegator.new(assertions) def things [:a] end } expect(klass.new).to have_thing(:a) expect(klass.new).not_to have_thing(:b) end it "does not delegate method_missing" do assertions = Module.new { def method_missing(method, *args) end } klass = Class.new { include RSpec::Rails::AssertionDelegator.new(assertions) } expect { klass.new.abc123 }.to raise_error(NoMethodError) end end rspec-rails-2.13.2/spec/rspec/rails/configuration_spec.rb000066400000000000000000000010771214604200000234030ustar00rootroot00000000000000require "spec_helper" describe "configuration" do before do @orig_render_views = RSpec.configuration.render_views? end after do RSpec.configuration.render_views = @orig_render_views end describe "#render_views?" do it "is false by default" do RSpec.configuration.render_views?.should be_false end end describe "#render_views" do it "sets render_views? to return true" do RSpec.configuration.render_views = false RSpec.configuration.render_views RSpec.configuration.render_views?.should be_true end end end rspec-rails-2.13.2/spec/rspec/rails/deprecations_spec.rb000066400000000000000000000006241214604200000232110ustar00rootroot00000000000000require 'spec_helper' describe "rspec-rails-2 deprecations" do context "controller specs" do describe "::integrate_views" do let(:group) do RSpec::Core::ExampleGroup.describe do include RSpec::Rails::ControllerExampleGroup end end it "is deprecated" do RSpec.should_receive(:deprecate) group.integrate_views end end end end rspec-rails-2.13.2/spec/rspec/rails/example/000077500000000000000000000000001214604200000206235ustar00rootroot00000000000000rspec-rails-2.13.2/spec/rspec/rails/example/controller_example_group_spec.rb000066400000000000000000000064021214604200000272760ustar00rootroot00000000000000require "spec_helper" class ::ApplicationController end module RSpec::Rails describe ControllerExampleGroup do it { should be_included_in_files_in('./spec/controllers/') } it { should be_included_in_files_in('.\\spec\\controllers\\') } let(:group) do RSpec::Core::ExampleGroup.describe do include ControllerExampleGroup end end it "includes routing matchers" do group.included_modules.should include(RSpec::Rails::Matchers::RoutingMatchers) end it "adds :type => :controller to the metadata" do group.metadata[:type].should eq(:controller) end context "with implicit subject" do it "uses the controller as the subject" do controller = double('controller') example = group.new example.stub(:controller => controller) example.subject.should == controller end end context "with explicit subject" do it "uses the specified subject instead of the controller" do group.subject { 'explicit' } example = group.new example.subject.should == 'explicit' end end describe "#controller" do before do group.class_eval do controller(Class.new) { } end end it "delegates named route helpers to the underlying controller" do controller = double('controller') controller.stub(:foos_url).and_return('http://test.host/foos') example = group.new example.stub(:controller => controller) # As in the routing example spec, this is pretty invasive, but not sure # how to do it any other way as the correct operation relies on before # hooks routes = ActionDispatch::Routing::RouteSet.new routes.draw { resources :foos } example.instance_variable_set(:@orig_routes, routes) example.foos_url.should eq('http://test.host/foos') end end describe "#bypass_rescue" do it "overrides the rescue_with_handler method on the controller to raise submitted error" do example = group.new example.instance_variable_set("@controller", Class.new { def rescue_with_handler(e); end }.new) example.bypass_rescue expect do example.controller.rescue_with_handler(RuntimeError.new("foo")) end.to raise_error("foo") end end describe "with inferred anonymous controller" do before do group.stub(:controller_class).and_return(Class.new) end it "infers the anonymous controller class when infer_base_class_for_anonymous_controllers is true" do RSpec.configuration.stub(:infer_base_class_for_anonymous_controllers?).and_return(true) group.controller { } controller_class = group.metadata[:example_group][:described_class] controller_class.superclass.should eq(group.controller_class) end it "sets the anonymous controller class to ApplicationController when infer_base_class_for_anonymous_controllers is false" do RSpec.configuration.stub(:infer_base_class_for_anonymous_controllers?).and_return(false) group.controller { } controller_class = group.metadata[:example_group][:described_class] controller_class.superclass.should eq(ApplicationController) end end end end rspec-rails-2.13.2/spec/rspec/rails/example/feature_example_group_spec.rb000066400000000000000000000027001214604200000265430ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe FeatureExampleGroup do it { should be_included_in_files_in('./spec/features/') } it { should be_included_in_files_in('.\\spec\\features\\') } it "adds :type => :feature to the metadata" do group = RSpec::Core::ExampleGroup.describe do include FeatureExampleGroup end expect(group.metadata[:type]).to eq(:feature) end it "includes Rails route helpers" do Rails.application.routes.draw do get "/foo", :as => :foo, :to => "foo#bar" end group = RSpec::Core::ExampleGroup.describe do include FeatureExampleGroup end expect(group.new.foo_path).to eq("/foo") expect(group.new.foo_url).to eq("http://www.example.com/foo") end describe "#visit" do it "raises an error informing about missing Capybara" do group = RSpec::Core::ExampleGroup.describe do include FeatureExampleGroup end expect { group.new.visit('/foobar') }.to raise_error(/Capybara not loaded/) end it "is resistant to load order errors" do capybara = Module.new do def visit(url) "success: #{url}" end end group = RSpec::Core::ExampleGroup.describe do include capybara include FeatureExampleGroup end expect(group.new.visit("/foo")).to eq("success: /foo") end end end end rspec-rails-2.13.2/spec/rspec/rails/example/helper_example_group_spec.rb000066400000000000000000000040071214604200000263710ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe HelperExampleGroup do module ::FoosHelper; end subject { HelperExampleGroup } it { should be_included_in_files_in('./spec/helpers/') } it { should be_included_in_files_in('.\\spec\\helpers\\') } it "provides a controller_path based on the helper module's name" do helper_spec = Object.new.extend HelperExampleGroup helper_spec.stub_chain(:example, :example_group, :described_class).and_return(FoosHelper) helper_spec.__send__(:_controller_path).should == "foos" end it "adds :type => :helper to the metadata" do group = RSpec::Core::ExampleGroup.describe do include HelperExampleGroup end group.metadata[:type].should eq(:helper) end describe "#helper" do it "returns the instance of AV::Base provided by AV::TC::Behavior" do helper_spec = Object.new.extend HelperExampleGroup helper_spec.should_receive(:view_assigns) av_tc_b_view = double('_view') av_tc_b_view.should_receive(:assign) helper_spec.stub(:_view) { av_tc_b_view } helper_spec.helper.should eq(av_tc_b_view) end before do Object.const_set(:ApplicationHelper, Module.new) end after do Object.__send__(:remove_const, :ApplicationHelper) end it "includes ApplicationHelper" do group = RSpec::Core::ExampleGroup.describe do include HelperExampleGroup def _view ActionView::Base.new end end group.new.helper.should be_kind_of(ApplicationHelper) end end end describe HelperExampleGroup::ClassMethods do describe "determine_default_helper_class" do it "returns the helper module passed to describe" do helper_spec = Object.new.extend HelperExampleGroup::ClassMethods helper_spec.stub(:described_class) { FoosHelper } helper_spec.determine_default_helper_class("ignore this"). should eq(FoosHelper) end end end end rspec-rails-2.13.2/spec/rspec/rails/example/mailer_example_group_spec.rb000066400000000000000000000011671214604200000263670ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe MailerExampleGroup do module ::Rails; end before do Rails.stub_chain(:application, :routes, :url_helpers).and_return(Rails) Rails.stub_chain(:configuration, :action_mailer, :default_url_options).and_return({}) end it { should be_included_in_files_in('./spec/mailers/') } it { should be_included_in_files_in('.\\spec\\mailers\\') } it "adds :type => :mailer to the metadata" do group = RSpec::Core::ExampleGroup.describe do include MailerExampleGroup end group.metadata[:type].should eq(:mailer) end end end rspec-rails-2.13.2/spec/rspec/rails/example/model_example_group_spec.rb000066400000000000000000000006301214604200000262100ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe ModelExampleGroup do it { should be_included_in_files_in('./spec/models/') } it { should be_included_in_files_in('.\\spec\\models\\') } it "adds :type => :model to the metadata" do group = RSpec::Core::ExampleGroup.describe do include ModelExampleGroup end group.metadata[:type].should eq(:model) end end end rspec-rails-2.13.2/spec/rspec/rails/example/request_example_group_spec.rb000066400000000000000000000010511214604200000265760ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe RequestExampleGroup do it { should be_included_in_files_in('./spec/requests/') } it { should be_included_in_files_in('./spec/integration/') } it { should be_included_in_files_in('.\\spec\\requests\\') } it { should be_included_in_files_in('.\\spec\\integration\\') } it "adds :type => :request to the metadata" do group = RSpec::Core::ExampleGroup.describe do include RequestExampleGroup end group.metadata[:type].should eq(:request) end end end rspec-rails-2.13.2/spec/rspec/rails/example/routing_example_group_spec.rb000066400000000000000000000015771214604200000266120ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe RoutingExampleGroup do it { should be_included_in_files_in('./spec/routing/') } it { should be_included_in_files_in('.\\spec\\routing\\') } it "adds :type => :routing to the metadata" do group = RSpec::Core::ExampleGroup.describe do include RoutingExampleGroup end group.metadata[:type].should eq(:routing) end describe "named routes" do it "delegates them to the route_set" do group = RSpec::Core::ExampleGroup.describe do include RoutingExampleGroup end example = group.new # Yes, this is quite invasive url_helpers = double('url_helpers', :foo_path => "foo") routes = double('routes', :url_helpers => url_helpers) example.stub(:routes => routes) example.foo_path.should == "foo" end end end end rspec-rails-2.13.2/spec/rspec/rails/example/view_example_group_spec.rb000066400000000000000000000144611214604200000260710ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe ViewExampleGroup do it { should be_included_in_files_in('./spec/views/') } it { should be_included_in_files_in('.\\spec\\views\\') } it "adds :type => :view to the metadata" do group = RSpec::Core::ExampleGroup.describe do include ViewExampleGroup end group.metadata[:type].should eq(:view) end describe 'automatic inclusion of helpers' do module ::ThingsHelper; end module ::Namespaced; module ThingsHelper; end; end it 'includes the helper with the same name' do group = RSpec::Core::ExampleGroup.describe 'things/show.html.erb' group.should_receive(:helper).with(ThingsHelper) group.class_eval do include ViewExampleGroup end end it 'includes the namespaced helper with the same name' do group = RSpec::Core::ExampleGroup.describe 'namespaced/things/show.html.erb' group.should_receive(:helper).with(Namespaced::ThingsHelper) group.class_eval do include ViewExampleGroup end end it 'operates normally when no helper with the same name exists' do raise 'unexpected constant found' if Object.const_defined?('ClocksHelper') lambda { RSpec::Core::ExampleGroup.describe 'clocks/show.html.erb' do include ViewExampleGroup end }.should_not raise_error end context 'application helper exists' do before do if !Object.const_defined? 'ApplicationHelper' module ::ApplicationHelper; end @application_helper_defined = true end end after do if @application_helper_defined Object.__send__ :remove_const, 'ApplicationHelper' end end it 'includes the application helper' do group = RSpec::Core::Example.describe 'bars/new.html.erb' group.should_receive(:helper).with(ApplicationHelper) group.class_eval do include ViewExampleGroup end end end context 'no application helper exists' do before do if Object.const_defined? 'ApplicationHelper' @application_helper = ApplicationHelper Object.__send__ :remove_const, 'ApplicationHelper' end end after do if @application_helper ApplicationHelper = @application_helper end end it 'operates normally' do lambda { RSpec::Core::ExampleGroup.describe 'foos/edit.html.erb' do include ViewExampleGroup end }.should_not raise_error end end end describe "#render" do let(:view_spec) do Class.new do module Local def received @received ||= [] end def render(options={}, local_assigns={}, &block) received << [options, local_assigns, block] end def _assigns {} end end include Local include ViewExampleGroup::ExampleMethods end.new end context "given no input" do it "sends render(:template => (described file)) to the view" do view_spec.stub(:_default_file_to_render) { "widgets/new" } view_spec.render view_spec.received.first.should == [{:template => "widgets/new"},{}, nil] end it "converts the filename components into render options" do view_spec.stub(:_default_file_to_render) { "widgets/new.en.html.erb" } view_spec.render if ::Rails::VERSION::STRING >= '3.2' view_spec.received.first.should == [{:template => "widgets/new", :locales=>['en'], :formats=>['html'], :handlers=>['erb']}, {}, nil] else view_spec.received.first.should == [{:template => "widgets/new.en.html.erb"}, {}, nil] end end end context "given a string" do it "sends string as the first arg to render" do view_spec.render('arbitrary/path') view_spec.received.first.should == ["arbitrary/path", {}, nil] end end context "given a hash" do it "sends the hash as the first arg to render" do view_spec.render(:foo => 'bar') view_spec.received.first.should == [{:foo => "bar"}, {}, nil] end end end describe '#params' do let(:view_spec) do Class.new do include ViewExampleGroup::ExampleMethods def controller @controller ||= Object.new end end.new end it 'delegates to the controller' do view_spec.controller.should_receive(:params).and_return({}) view_spec.params[:foo] = 1 end end describe "#_controller_path" do let(:view_spec) do Class.new do include ViewExampleGroup::ExampleMethods end.new end context "with a common _default_file_to_render" do it "it returns the directory" do view_spec.stub(:_default_file_to_render). and_return("things/new.html.erb") view_spec.__send__(:_controller_path). should == "things" end end context "with a nested _default_file_to_render" do it "it returns the directory path" do view_spec.stub(:_default_file_to_render). and_return("admin/things/new.html.erb") view_spec.__send__(:_controller_path). should == "admin/things" end end end describe "#view" do let(:view_spec) do Class.new do include ViewExampleGroup::ExampleMethods end.new end it "delegates to _view" do view = double("view") view_spec.stub(:_view) { view } view_spec.view.should == view end end describe "#template" do let(:view_spec) do Class.new do include ViewExampleGroup::ExampleMethods def _view; end end.new end before { RSpec.stub(:deprecate) } it "is deprecated" do RSpec.should_receive(:deprecate) view_spec.template end it "delegates to #view" do view_spec.should_receive(:view) view_spec.template end end end end rspec-rails-2.13.2/spec/rspec/rails/extensions/000077500000000000000000000000001214604200000213675ustar00rootroot00000000000000rspec-rails-2.13.2/spec/rspec/rails/extensions/active_model/000077500000000000000000000000001214604200000240225ustar00rootroot00000000000000rspec-rails-2.13.2/spec/rspec/rails/extensions/active_model/errors_on_spec.rb000066400000000000000000000006651214604200000274000ustar00rootroot00000000000000require "spec_helper" describe "errors_on" do let(:klass) do Class.new do include ActiveModel::Validations end end it "calls valid?" do model = klass.new model.should_receive(:valid?) model.errors_on(:foo) end it "returns the errors on that attribute" do model = klass.new model.stub(:errors) do { :foo => ['a', 'b'] } end model.errors_on(:foo).should eq(['a','b']) end end rspec-rails-2.13.2/spec/rspec/rails/extensions/active_record/000077500000000000000000000000001214604200000242005ustar00rootroot00000000000000rspec-rails-2.13.2/spec/rspec/rails/extensions/active_record/base_spec.rb000066400000000000000000000015641214604200000264570ustar00rootroot00000000000000require 'spec_helper' describe ::ActiveModel::Validations do describe "#errors_on" do context "ActiveModel class that takes no arguments to valid?" do let(:klass) { Class.new do include ActiveModel::Validations def self.name "ActiveModelValidationsFake" end def valid? super end attr_accessor :name validates_presence_of :name end } context "with nil name" do it "has one error" do object = klass.new object.name = "" expect(object).to have(1).error_on(:name) end end context "with non-blank name" do it "has no error" do object = klass.new object.name = "Ywen" expect(object).to have(:no).error_on(:name) end end end end end rspec-rails-2.13.2/spec/rspec/rails/extensions/active_record/records_spec.rb000066400000000000000000000003001214604200000271710ustar00rootroot00000000000000require 'spec_helper' describe "records" do it "delegates to find(:all)" do klass = Class.new(ActiveRecord::Base) klass.should_receive(:find).with(:all) klass.records end end rspec-rails-2.13.2/spec/rspec/rails/fixture_support_spec.rb000066400000000000000000000007271214604200000240170ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe FixtureSupport do context "with use_transactional_fixtures set to false" do it "still supports fixture_path" do RSpec.configuration.stub(:use_transactional_fixtures) { false } group = RSpec::Core::ExampleGroup.describe do include FixtureSupport end group.should respond_to(:fixture_path) group.should respond_to(:fixture_path=) end end end end rspec-rails-2.13.2/spec/rspec/rails/matchers/000077500000000000000000000000001214604200000207765ustar00rootroot00000000000000rspec-rails-2.13.2/spec/rspec/rails/matchers/be_a_new_spec.rb000066400000000000000000000071561214604200000241050ustar00rootroot00000000000000require "spec_helper" describe "be_a_new matcher" do include RSpec::Rails::Matchers context "new record" do let(:record) do Class.new do def new_record?; true; end end.new end context "right class" do it "passes" do record.should be_a_new(record.class) end end context "wrong class" do it "fails" do record.should_not be_a_new(String) end end end context "existing record" do let(:record) do Class.new do def new_record?; false; end end.new end context "right class" do it "fails" do record.should_not be_a_new(record.class) end end context "wrong class" do it "fails" do record.should_not be_a_new(String) end end end describe "#with" do context "right class and new record" do let(:record) do Class.new do def initialize(attributes) @attributes = attributes end def attributes @attributes.stringify_keys end def new_record?; true; end end.new(:foo => 'foo', :bar => 'bar') end context "all attributes same" do it "passes" do record.should be_a_new(record.class).with(:foo => 'foo', :bar => 'bar') end end context "one attribute same" do it "passes" do record.should be_a_new(record.class).with(:foo => 'foo') end end context "no attributes same" do it "fails" do expect { record.should be_a_new(record.class).with(:zoo => 'zoo', :car => 'car') }.to raise_error {|e| e.message.should match(/attributes {.*} were not set on #{record.inspect}/) e.message.should match(/"zoo"=>"zoo"/) e.message.should match(/"car"=>"car"/) } end end context "one attribute value not the same" do it "fails" do expect { record.should be_a_new(record.class).with(:foo => 'bar') }.to raise_error( %Q(attribute {"foo"=>"bar"} was not set on #{record.inspect}) ) end end end context "wrong class and existing record" do let(:record) do Class.new do def initialize(attributes) @attributes = attributes end def attributes @attributes.stringify_keys end def new_record?; false; end end.new(:foo => 'foo', :bar => 'bar') end context "all attributes same" do it "fails" do expect { record.should be_a_new(String).with(:foo => 'foo', :bar => 'bar') }.to raise_error( "expected #{record.inspect} to be a new String" ) end end context "no attributes same" do it "fails" do expect { record.should be_a_new(String).with(:zoo => 'zoo', :car => 'car') }.to raise_error {|e| e.message.should match(/expected #{record.inspect} to be a new String and attributes {.*} were not set on #{record.inspect}/) e.message.should match(/"zoo"=>"zoo"/) e.message.should match(/"car"=>"car"/) } end end context "one attribute value not the same" do it "fails" do expect { record.should be_a_new(String).with(:foo => 'bar') }.to raise_error( "expected #{record.inspect} to be a new String and " + %Q(attribute {"foo"=>"bar"} was not set on #{record.inspect}) ) end end end end end rspec-rails-2.13.2/spec/rspec/rails/matchers/be_new_record_spec.rb000066400000000000000000000014371214604200000251370ustar00rootroot00000000000000require "spec_helper" describe "be_new_record" do include RSpec::Rails::Matchers context "un-persisted record" do let(:record) { double('record', :persisted? => false) } it "passes" do record.should be_new_record end it "fails with custom failure message" do expect { expect(record).not_to be_new_record }.to raise_exception(/expected .* to be persisted, but was a new record/) end end context "persisted record" do let(:record) { double('record', :persisted? => true) } it "fails" do record.should_not be_new_record end it "fails with custom failure message" do expect { expect(record).to be_new_record }.to raise_exception(/expected .* to be a new record, but was persisted/) end end end rspec-rails-2.13.2/spec/rspec/rails/matchers/be_routable_spec.rb000066400000000000000000000023701214604200000246220ustar00rootroot00000000000000require "spec_helper" describe "be_routable" do include RSpec::Rails::Matchers::RoutingMatchers attr_reader :routes before { @routes = double("routes") } context "with should" do it "passes if routes recognize the path" do routes.stub(:recognize_path) { {} } expect do {:get => "/a/path"}.should be_routable end.to_not raise_error end it "fails if routes do not recognize the path" do routes.stub(:recognize_path) { raise ActionController::RoutingError.new('ignore') } expect do {:get => "/a/path"}.should be_routable end.to raise_error(/expected \{:get=>"\/a\/path"\} to be routable/) end end context "with should_not" do it "passes if routes do not recognize the path" do routes.stub(:recognize_path) { raise ActionController::RoutingError.new('ignore') } expect do {:get => "/a/path"}.should_not be_routable end.to_not raise_error end it "fails if routes recognize the path" do routes.stub(:recognize_path) { {:controller => "foo"} } expect do {:get => "/a/path"}.should_not be_routable end.to raise_error(/expected \{:get=>"\/a\/path"\} not to be routable, but it routes to \{:controller=>"foo"\}/) end end end rspec-rails-2.13.2/spec/rspec/rails/matchers/be_valid_spec.rb000066400000000000000000000022001214604200000240740ustar00rootroot00000000000000require "spec_helper" require 'active_support/all' require 'rspec/rails/matchers/be_valid' describe "be_valid matcher" do include RSpec::Rails::Matchers class Post include ActiveModel::Validations attr_accessor :title validates_presence_of :title end let(:post) { Post.new } it "includes the error messages in the failure message" do expect { expect(post).to be_valid }.to raise_exception(/Title can't be blank/) end it "includes a failure message for the negative case" do post.stub(:valid?) { true } expect { expect(post).not_to be_valid }.to raise_exception(/expected .* not to be valid/) end it "uses a custom failure message if provided" do expect { expect(post).to be_valid, "Post was not valid!" }.to raise_exception(/Post was not valid!/) end it "includes the validation context if provided" do post.should_receive(:valid?).with(:create) { true } expect(post).to be_valid(:create) end it "does not include the validation context if not provided" do post.should_receive(:valid?).with(no_args) { true } expect(post).to be_valid end end rspec-rails-2.13.2/spec/rspec/rails/matchers/errors_on_spec.rb000066400000000000000000000022021214604200000243410ustar00rootroot00000000000000require "spec_helper" describe "error_on" do it "provides a description including the name of what the error is on" do have(1).error_on(:whatever).description.should == "have 1 error on :whatever" end it "provides a failure message including the number actually given" do lambda { [].should have(1).error_on(:whatever) }.should raise_error("expected 1 error on :whatever, got 0") end end describe "errors_on" do it "provides a description including the name of what the error is on" do have(2).errors_on(:whatever).description.should == "have 2 errors on :whatever" end it "provides a failure message including the number actually given" do lambda { [1].should have(3).errors_on(:whatever) }.should raise_error("expected 3 errors on :whatever, got 1") end end describe "have something other than error_on or errors_on" do it "has a standard rspec failure message" do lambda { [1,2,3].should have(2).elements }.should raise_error("expected 2 elements, got 3") end it "has a standard rspec description" do have(2).elements.description.should == "have 2 elements" end end rspec-rails-2.13.2/spec/rspec/rails/matchers/has_spec.rb000066400000000000000000000012521214604200000231100ustar00rootroot00000000000000require 'spec_helper' class CollectionOwner < ActiveRecord::Base connection.execute <<-SQL CREATE TABLE collection_owners ( id integer PRIMARY KEY AUTOINCREMENT ) SQL has_many :associated_items do def has_some_quality?; true end end end class AssociatedItem < ActiveRecord::Base connection.execute <<-SQL CREATE TABLE associated_items ( id integer PRIMARY KEY AUTOINCREMENT, collection_owner_id integer ) SQL belongs_to :collection_owner end describe "should have_xxx" do it "works with ActiveRecord::Associations::CollectionProxy" do owner = CollectionOwner.new owner.associated_items.should have_some_quality end end rspec-rails-2.13.2/spec/rspec/rails/matchers/have_rendered_spec.rb000066400000000000000000000060601214604200000251320ustar00rootroot00000000000000require "spec_helper" %w[have_rendered render_template].each do |template_expectation| describe template_expectation do include RSpec::Rails::Matchers::RenderTemplate let(:response) { ActionController::TestResponse.new } context "given a hash" do it "delegates to assert_template" do self.should_receive(:assert_template).with({:this => "hash"}, "this message") expect("response").to send(template_expectation, {:this => "hash"}, "this message") end end context "given a string" do it "delegates to assert_template" do self.should_receive(:assert_template).with("this string", "this message") expect("response").to send(template_expectation, "this string", "this message") end end context "given a symbol" do it "converts to_s and delegates to assert_template" do self.should_receive(:assert_template).with("template_name", "this message") expect("response").to send(template_expectation, :template_name, "this message") end end context "with should" do context "when assert_template passes" do it "passes" do def assert_template(*); end expect do expect(response).to send(template_expectation, "template_name") end.to_not raise_exception end end context "when assert_template fails" do it "uses failure message from assert_template" do def assert_template(*) raise ActiveSupport::TestCase::Assertion.new("this message") end expect do expect(response).to send(template_expectation, "template_name") end.to raise_error("this message") end end context "when fails due to some other exception" do it "raises that exception" do def assert_template(*) raise "oops" end expect do expect(response).to send(template_expectation, "template_name") end.to raise_exception("oops") end end end context "with should_not" do context "when assert_template fails" do it "passes" do def assert_template(*) raise ActiveSupport::TestCase::Assertion.new("this message") end expect do expect(response).to_not send(template_expectation, "template_name") end.to_not raise_exception end end context "when assert_template passes" do it "fails with custom failure message" do def assert_template(*); end expect do expect(response).to_not send(template_expectation, "template_name") end.to raise_error(/expected not to render \"template_name\", but did/) end end context "when fails due to some other exception" do it "raises that exception" do def assert_template(*); raise "oops"; end expect do expect(response).to_not send(template_expectation, "template_name") end.to raise_exception("oops") end end end end end rspec-rails-2.13.2/spec/rspec/rails/matchers/redirect_to_spec.rb000066400000000000000000000040231214604200000246370ustar00rootroot00000000000000require "spec_helper" require "active_support/test_case" describe "redirect_to" do include RSpec::Rails::Matchers::RedirectTo let(:response) { ActionController::TestResponse.new } context "with should" do context "when assert_redirected_to passes" do def assert_redirected_to(*); end it "passes" do expect do response.should redirect_to("destination") end.to_not raise_exception end end context "when assert_redirected_to fails" do def assert_redirected_to(*) raise ActiveSupport::TestCase::Assertion.new("this message") end it "uses failure message from assert_redirected_to" do expect do response.should redirect_to("destination") end.to raise_exception("this message") end end context "when fails due to some other exception" do def assert_redirected_to(*) raise "oops" end it "raises that exception" do expect do response.should redirect_to("destination") end.to raise_exception("oops") end end end context "with should_not" do context "when assert_redirected_to fails" do def assert_redirected_to(*) raise ActiveSupport::TestCase::Assertion.new("this message") end it "passes" do expect do response.should_not redirect_to("destination") end.to_not raise_exception end end context "when assert_redirected_to passes" do def assert_redirected_to(*); end it "fails with custom failure message" do expect do response.should_not redirect_to("destination") end.to raise_exception(/expected not to redirect to \"destination\", but did/) end end context "when fails due to some other exception" do def assert_redirected_to(*) raise "oops" end it "raises that exception" do expect do response.should_not redirect_to("destination") end.to raise_exception("oops") end end end end rspec-rails-2.13.2/spec/rspec/rails/matchers/relation_match_array_spec.rb000066400000000000000000000020341214604200000265230ustar00rootroot00000000000000require "spec_helper" describe "ActiveSupport::Relation =~ matcher" do before { MockableModel.delete_all } let!(:models) { Array.new(3) { MockableModel.create } } if ::Rails::VERSION::STRING >= '4' it "verifies that the scope returns the records on the right hand side, regardless of order" do MockableModel.all.should =~ models.reverse end it "fails if the scope encompasses more records than on the right hand side" do MockableModel.create MockableModel.all.should_not =~ models.reverse end else it "verifies that the scope returns the records on the right hand side, regardless of order" do MockableModel.scoped.should =~ models.reverse end it "fails if the scope encompasses more records than on the right hand side" do MockableModel.create MockableModel.scoped.should_not =~ models.reverse end end it "fails if the scope encompasses fewer records than on the right hand side" do MockableModel.limit(models.length - 1).should_not =~ models.reverse end end rspec-rails-2.13.2/spec/rspec/rails/matchers/route_to_spec.rb000066400000000000000000000116231214604200000242000ustar00rootroot00000000000000require "spec_helper" describe "route_to" do include RSpec::Rails::Matchers::RoutingMatchers include RSpec::Rails::Matchers::RoutingMatchers::RouteHelpers def assert_recognizes(*) # no-op end it "provides a description" do matcher = route_to("these" => "options") matcher.matches?(:get => "path") matcher.description.should == "route {:get=>\"path\"} to {\"these\"=>\"options\"}" end it "delegates to assert_recognizes" do self.should_receive(:assert_recognizes).with({ "these" => "options" }, { :method=> :get, :path=>"path" }, {}) {:get => "path"}.should route_to("these" => "options") end context "with shortcut syntax" do it "routes with extra options" do self.should_receive(:assert_recognizes).with({ :controller => "controller", :action => "action", :extra => "options"}, { :method=> :get, :path=>"path" }, {}) get("path").should route_to("controller#action", :extra => "options") end it "routes without extra options" do self.should_receive(:assert_recognizes).with( {:controller => "controller", :action => "action"}, {:method=> :get, :path=>"path" }, {} ) get("path").should route_to("controller#action") end it "routes with one query parameter" do self.should_receive(:assert_recognizes).with( {:controller => "controller", :action => "action", :queryitem => "queryvalue"}, {:method=> :get, :path=>"path" }, {'queryitem' => 'queryvalue' } ) get("path?queryitem=queryvalue").should route_to("controller#action", :queryitem => 'queryvalue') end it "routes with multiple query parameters" do self.should_receive(:assert_recognizes).with( {:controller => "controller", :action => "action", :queryitem => "queryvalue", :qi2 => 'qv2'}, {:method=> :get, :path=>"path"}, {'queryitem' => 'queryvalue', 'qi2' => 'qv2'} ) get("path?queryitem=queryvalue&qi2=qv2").should route_to("controller#action", :queryitem => 'queryvalue', :qi2 => 'qv2') end end context "with should" do context "when assert_recognizes passes" do it "passes" do expect do {:get => "path"}.should route_to("these" => "options") end.to_not raise_exception end end context "when assert_recognizes fails with an assertion failure" do it "fails with message from assert_recognizes" do def assert_recognizes(*) raise ActiveSupport::TestCase::Assertion.new("this message") end expect do {:get => "path"}.should route_to("these" => "options") end.to raise_error(RSpec::Expectations::ExpectationNotMetError, "this message") end end context "when assert_recognizes fails with a routing error" do it "fails with message from assert_recognizes" do def assert_recognizes(*) raise ActionController::RoutingError.new("this message") end expect do {:get => "path"}.should route_to("these" => "options") end.to raise_error(RSpec::Expectations::ExpectationNotMetError, "this message") end end context "when an exception is raised" do it "raises that exception" do def assert_recognizes(*) raise "oops" end expect do {:get => "path"}.should route_to("these" => "options") end.to raise_exception("oops") end end end context "with should_not" do context "when assert_recognizes passes" do it "fails with custom message" do expect do {:get => "path"}.should_not route_to("these" => "options") end.to raise_error(/expected .* not to route to .*/) end end context "when assert_recognizes fails with an assertion failure" do it "passes" do def assert_recognizes(*) raise ActiveSupport::TestCase::Assertion.new("this message") end expect do {:get => "path"}.should_not route_to("these" => "options") end.to_not raise_error end end context "when assert_recognizes fails with a routing error" do it "passes" do def assert_recognizes(*) raise ActionController::RoutingError.new("this message") end expect do {:get => "path"}.should_not route_to("these" => "options") end.to_not raise_error end end context "when an exception is raised" do it "raises that exception" do def assert_recognizes(*) raise "oops" end expect do {:get => "path"}.should_not route_to("these" => "options") end.to raise_exception("oops") end end end it "uses failure message from assert_recognizes" do def assert_recognizes(*) raise ActiveSupport::TestCase::Assertion, "this message" end expect do {"this" => "path"}.should route_to("these" => "options") end.to raise_error("this message") end end rspec-rails-2.13.2/spec/rspec/rails/minitest_lifecycle_adapter_spec.rb000066400000000000000000000014731214604200000261070ustar00rootroot00000000000000require "spec_helper" describe RSpec::Rails::MiniTestLifecycleAdapter do it "invokes minitest lifecycle hooks at the appropriate times" do invocations = [] example_group = RSpec::Core::ExampleGroup.describe("MiniTestHooks") do include RSpec::Rails::MiniTestLifecycleAdapter define_method(:before_setup) { invocations << :before_setup } define_method(:after_setup) { invocations << :after_setup } define_method(:before_teardown) { invocations << :before_teardown } define_method(:after_teardown) { invocations << :after_teardown } end example = example_group.example("foo") { invocations << :example } example_group.run(NullObject.new) expect(invocations).to eq([ :before_setup, :after_setup, :example, :before_teardown, :after_teardown ]) end end rspec-rails-2.13.2/spec/rspec/rails/mocks/000077500000000000000000000000001214604200000203045ustar00rootroot00000000000000rspec-rails-2.13.2/spec/rspec/rails/mocks/mock_model_spec.rb000066400000000000000000000250011214604200000237520ustar00rootroot00000000000000require 'spec_helper' describe "mock_model(RealModel)" do context "given a String" do context "that does not represent an existing constant" do it "class says it's name" do model = mock_model("Foo") model.class.name.should eq("Foo") end end context "that represents an existing constant" do context "that extends ActiveModel::Naming" do it "treats the constant as the class" do model = mock_model("MockableModel") model.class.name.should eq("MockableModel") end end context "that does not extend ActiveModel::Naming" do it "raises with a helpful message" do expect do mock_model("String") end.to raise_error(ArgumentError) end end end end context "given a class that does not extend ActiveModel::Naming" do it "raises with a helpful message" do expect do mock_model(String) end.to raise_error(ArgumentError) end end describe "with #id stubbed" do before(:each) do @model = mock_model(MockableModel, :id => 1) end it "is named using the stubbed id value" do @model.instance_variable_get(:@name).should == "MockableModel_1" end end describe "destroy" do it "sets persisted to false" do model = mock_model(MockableModel) model.destroy model.should_not be_persisted end end describe "errors" do context "default" do it "is empty" do model = mock_model(MockableModel) model.errors.should be_empty end end context "with :save => false" do it "is not empty" do model = mock_model(MockableModel, :save => false) model.errors.should_not be_empty end end context "with :update_attributes => false" do it "is not empty" do model = mock_model(MockableModel, :save => false) model.errors.should_not be_empty end end end describe "with params" do it "does not mutate its parameters" do params = {:a => 'b'} mock_model(MockableModel, params) params.should == {:a => 'b'} end end describe "as association" do before(:each) do @real = AssociatedModel.create! @mock_model = mock_model(MockableModel) @real.mockable_model = @mock_model end it "passes: associated_model == mock" do @mock_model.should == @real.mockable_model end it "passes: mock == associated_model" do @real.mockable_model.should == @mock_model end end describe "as association that doesn't exist yet" do before(:each) do @real = AssociatedModel.create! @mock_model = mock_model("Other") @real.nonexistent_model = @mock_model end it "passes: associated_model == mock" do @mock_model.should == @real.nonexistent_model end it "passes: mock == associated_model" do @real.nonexistent_model.should == @mock_model end end describe "#is_a?" do before(:each) do @model = mock_model(SubMockableModel) end it "says it is_a?(RealModel)" do @model.is_a?(SubMockableModel).should be(true) end it "says it is_a?(OtherModel) if RealModel is an ancestors" do @model.is_a?(MockableModel).should be(true) end it "can be stubbed" do mock_model(MockableModel, :is_a? => true).is_a?(:Foo).should be_true end end describe "#kind_of?" do before(:each) do @model = mock_model(SubMockableModel) end it "says it is kind_of? if RealModel is" do @model.kind_of?(SubMockableModel).should be(true) end it "says it is kind_of? if RealModel's ancestor is" do @model.kind_of?(MockableModel).should be(true) end it "can be stubbed" do mock_model(MockableModel, :kind_of? => true).kind_of?(:Foo).should be_true end end describe "#instance_of?" do before(:each) do @model = mock_model(SubMockableModel) end it "says it is instance_of? if RealModel is" do @model.instance_of?(SubMockableModel).should be(true) end it "does not say it instance_of? if RealModel isn't, even if it's ancestor is" do @model.instance_of?(MockableModel).should be(false) end it "can be stubbed" do mock_model(MockableModel, :instance_of? => true).instance_of?(:Foo).should be_true end end describe "#respond_to?" do context "with an ActiveRecord model" do before(:each) do MockableModel.stub(:column_names).and_return(["column_a", "column_b"]) @model = mock_model(MockableModel) end it "accepts two arguments" do expect do @model.respond_to?("title_before_type_cast", false) end.to_not raise_exception end context "without as_null_object" do it "says it will respond_to?(key) if RealModel has the attribute 'key'" do @model.respond_to?("column_a").should be(true) end it "stubs column accessor (with string)" do @model.respond_to?("column_a") @model.column_a.should be_nil end it "stubs column accessor (with symbol)" do @model.respond_to?(:column_a) @model.column_a.should be_nil end it "does not stub column accessor if already stubbed in declaration (with string)" do model = mock_model(MockableModel, "column_a" => "a") model.respond_to?("column_a") model.column_a.should eq("a") end it "does not stub column accessor if already stubbed in declaration (with symbol)" do model = mock_model(MockableModel, :column_a => "a") model.respond_to?("column_a") model.column_a.should eq("a") end it "does not stub column accessor if already stubbed after declaration (with string)" do @model.stub("column_a" => "a") @model.respond_to?("column_a") @model.column_a.should eq("a") end it "does not stub column accessor if already stubbed after declaration (with symbol)" do @model.stub(:column_a => "a") @model.respond_to?("column_a") @model.column_a.should eq("a") end it "says it will not respond_to?(key) if RealModel does not have the attribute 'key'" do @model.respond_to?("column_c").should be(false) end it "says it will not respond_to?(xxx_before_type_cast)" do @model.respond_to?("title_before_type_cast").should be(false) end end context "with as_null_object" do it "says it will respond_to?(key) if RealModel has the attribute 'key'" do @model.as_null_object.respond_to?("column_a").should be(true) end it "says it will respond_to?(key) even if RealModel does not have the attribute 'key'" do @model.as_null_object.respond_to?("column_c").should be(true) end it "says it will not respond_to?(xxx_before_type_cast)" do @model.as_null_object.respond_to?("title_before_type_cast").should be(false) end it "returns self for any unprepared message" do @model.as_null_object.tap do |x| x.non_existant_message.should be(@model) end end end end context "with a non-ActiveRecord model" do it "responds as normal" do model = NonActiveRecordModel.new model.should respond_to(:to_param) end context "with as_null_object" do it "says it will not respond_to?(xxx_before_type_cast)" do model = NonActiveRecordModel.new.as_null_object model.respond_to?("title_before_type_cast").should be(false) end end end it "can be stubbed" do mock_model(MockableModel, :respond_to? => true).respond_to?(:foo).should be_true end end describe "#class" do it "returns the mocked model" do mock_model(MockableModel).class.should eq(MockableModel) end it "can be stubbed" do mock_model(MockableModel, :class => String).class.should be(String) end end describe "#to_s" do it "returns (model.name)_(model#to_param)" do mock_model(MockableModel).to_s.should == "MockableModel_#{to_param}" end it "can be stubbed" do mock_model(MockableModel, :to_s => "this string").to_s.should == "this string" end end describe "#destroyed?" do context "default" do it "returns false" do @model = mock_model(SubMockableModel) @model.destroyed?.should be(false) end end end describe "#marked_for_destruction?" do context "default" do it "returns false" do @model = mock_model(SubMockableModel) @model.marked_for_destruction?.should be(false) end end end describe "#persisted?" do context "with default identifier" do it "returns true" do mock_model(MockableModel).should be_persisted end end context "with explicit identifier via :id" do it "returns true" do mock_model(MockableModel, :id => 37).should be_persisted end end context "with id => nil" do it "returns false" do mock_model(MockableModel, :id => nil).should_not be_persisted end end end describe "#valid?" do context "default" do it "returns true" do mock_model(MockableModel).should be_valid end end context "stubbed with false" do it "returns false" do mock_model(MockableModel, :valid? => false).should_not be_valid end end end describe "#as_new_record" do it "says it is a new record" do m = mock_model(MockableModel) m.as_new_record.should be_new_record end it "says it is not persisted" do m = mock_model(MockableModel) m.as_new_record.should_not be_persisted end it "has a nil id" do mock_model(MockableModel).as_new_record.id.should be(nil) end it "returns nil for #to_param" do mock_model(MockableModel).as_new_record.to_param.should be(nil) end end describe "#blank?" do it "is false" do mock_model(MockableModel).should_not be_blank end end describe "ActiveModel Lint tests" do require 'test/unit/assertions' require 'active_model/lint' include Test::Unit::Assertions include ActiveModel::Lint::Tests # to_s is to support ruby-1.9 ActiveModel::Lint::Tests.public_instance_methods.map{|m| m.to_s}.grep(/^test/).each do |m| example m.gsub('_',' ') do send m end end def model mock_model(MockableModel, :id => nil) end end end rspec-rails-2.13.2/spec/rspec/rails/mocks/stub_model_spec.rb000066400000000000000000000076151214604200000240110ustar00rootroot00000000000000require 'spec_helper' describe "stub_model" do shared_examples_for "stub model" do describe "with a block" do it "yields the model" do model = stub_model(model_class) do |block_arg| @block_arg = block_arg end model.should be(@block_arg) end end describe "#persisted?" do context "default" do it "returns true" do model = stub_model(model_class) model.should be_persisted end end context "with as_new_record" do it "returns false" do model = stub_model(model_class).as_new_record model.should_not be_persisted end end end it "increments the value returned by to_param" do first = stub_model(model_class) second = stub_model(model_class) second.to_param.to_i.should == (first.to_param.to_i + 1) end describe "#blank?" do it "is false" do stub_model(model_class).should_not be_blank end end end context "with ActiveModel (not ActiveRecord)" do it_behaves_like "stub model" do def model_class NonActiveRecordModel end end end context "with an ActiveRecord model" do let(:model_class) { MockableModel } it_behaves_like "stub model" describe "#new_record?" do context "default" do it "returns false" do model = stub_model(model_class) model.new_record?.should be_false end end context "with as_new_record" do it "returns true" do model = stub_model(model_class).as_new_record model.new_record?.should be_true end end end describe "defaults" do it "has an id" do stub_model(MockableModel).id.should be > 0 end it "says it is not a new record" do stub_model(MockableModel).should_not be_new_record end end describe "#as_new_record" do it "has a nil id" do stub_model(MockableModel).as_new_record.id.should be(nil) end end it "raises when hitting the db" do lambda do stub_model(MockableModel).connection end.should raise_error(RSpec::Rails::IllegalDataAccessException, /stubbed models are not allowed to access the database/) end it "increments the id" do first = stub_model(model_class) second = stub_model(model_class) second.id.should == (first.id + 1) end it "accepts a stub id" do stub_model(MockableModel, :id => 37).id.should == 37 end it "says it is a new record when id is set to nil" do stub_model(MockableModel, :id => nil).should be_new_record end it "accepts a stub for save" do stub_model(MockableModel, :save => false).save.should be(false) end describe "alternate primary key" do it "has the correct primary_key name" do stub_model(AlternatePrimaryKeyModel).class.primary_key.to_s.should eq('my_id') end it "has a primary_key" do stub_model(AlternatePrimaryKeyModel).my_id.should be > 0 end it "says it is not a new record" do stub_model(AlternatePrimaryKeyModel) do |m| m.should_not be_new_record end end it "says it is a new record if primary_key is nil" do stub_model(AlternatePrimaryKeyModel, :my_id => nil).should be_new_record end it "accepts a stub for the primary_key" do stub_model(AlternatePrimaryKeyModel, :my_id => 5).my_id.should == 5 end end describe "as association" do before(:each) do @real = AssociatedModel.create! @stub_model = stub_model(MockableModel) @real.mockable_model = @stub_model end it "passes associated_model == mock" do @stub_model.should == @real.mockable_model end it "passes mock == associated_model" do @real.mockable_model.should == @stub_model end end end end rspec-rails-2.13.2/spec/rspec/rails/setup_and_teardown_adapter_spec.rb000066400000000000000000000021711214604200000261150ustar00rootroot00000000000000require 'spec_helper' describe RSpec::Rails::SetupAndTeardownAdapter do describe "::setup" do it "registers before hooks in the order setup is received" do klass = Class.new do include RSpec::Rails::SetupAndTeardownAdapter def self.foo; "foo"; end def self.bar; "bar"; end end klass.should_receive(:before).ordered { |&block| block.call.should eq "foo" } klass.should_receive(:before).ordered { |&block| block.call.should eq "bar" } klass.setup :foo klass.setup :bar end it "registers prepend_before hooks for the Rails' setup methods" do klass = Class.new do include RSpec::Rails::SetupAndTeardownAdapter def self.setup_fixtures; "setup fixtures" end def self.setup_controller_request_and_response; "setup controller" end end klass.should_receive(:prepend_before) { |&block| block.call.should eq "setup fixtures" } klass.should_receive(:prepend_before) { |&block| block.call.should eq "setup controller" } klass.setup :setup_fixtures klass.setup :setup_controller_request_and_response end end end rspec-rails-2.13.2/spec/rspec/rails/view_rendering_spec.rb000066400000000000000000000057301214604200000235430ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe ViewRendering do let(:group) do RSpec::Core::ExampleGroup.describe do def controller ActionController::Base.new end include ViewRendering end end context "default" do context "ActionController::Base" do it "does not render views" do group.new.render_views?.should be_false end it "does not render views in a nested group" do group.describe{}.new.render_views?.should be_false end end context "ActionController::Metal" do it "renders views" do group.new.tap do |example| def example.controller ActionController::Metal.new end example.render_views?.should be_true end end end end describe "#render_views" do context "with no args" do it "tells examples to render views" do group.render_views group.new.render_views?.should be_true end end context "with true" do it "tells examples to render views" do group.render_views true group.new.render_views?.should be_true end end context "with false" do it "tells examples not to render views" do group.render_views false group.new.render_views?.should be_false end it "overrides the global config if render_views is enabled there" do RSpec.configuration.stub(:render_views?).and_return true group.render_views false group.new.render_views?.should be_false end end context "in a nested group" do let(:nested_group) do group.describe{} end context "with no args" do it "tells examples to render views" do nested_group.render_views nested_group.new.render_views?.should be_true end end context "with true" do it "tells examples to render views" do nested_group.render_views true nested_group.new.render_views?.should be_true end end context "with false" do it "tells examples not to render views" do nested_group.render_views false nested_group.new.render_views?.should be_false end end it "leaves the parent group as/is" do group.render_views nested_group.render_views false group.new.render_views?.should be_true end it "overrides the value inherited from the parent group" do group.render_views nested_group.render_views false nested_group.new.render_views?.should be_false end it "passes override to children" do group.render_views nested_group.render_views false nested_group.describe{}.new.render_views?.should be_false end end end end end rspec-rails-2.13.2/spec/spec_helper.rb000066400000000000000000000013761214604200000175670ustar00rootroot00000000000000require 'rails/all' module RSpecRails class Application < ::Rails::Application end end require 'rspec/rails' require 'ammeter/init' Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} class RSpec::Core::ExampleGroup def self.run_all(reporter=nil) run(reporter || RSpec::Mocks::Mock.new('reporter').as_null_object) end end RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true config.filter_run :focus config.run_all_when_everything_filtered = true config.before(:each) do @real_world = RSpec.world RSpec.instance_variable_set(:@world, RSpec::Core::World.new) end config.after(:each) do RSpec.instance_variable_set(:@world, @real_world) end config.order = :random end rspec-rails-2.13.2/spec/support/000077500000000000000000000000001214604200000164565ustar00rootroot00000000000000rspec-rails-2.13.2/spec/support/ar_classes.rb000066400000000000000000000016461214604200000211310ustar00rootroot00000000000000ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => ':memory:' ) module Connections def self.extended(host) host.connection.execute <<-eosql CREATE TABLE #{host.table_name} ( #{host.primary_key} integer PRIMARY KEY AUTOINCREMENT, associated_model_id integer, mockable_model_id integer, nonexistent_model_id integer ) eosql end end class NonActiveRecordModel extend ActiveModel::Naming include ActiveModel::Conversion end class MockableModel < ActiveRecord::Base extend Connections has_one :associated_model end class SubMockableModel < MockableModel end class AssociatedModel < ActiveRecord::Base extend Connections belongs_to :mockable_model belongs_to :nonexistent_model, :class_name => "Other" end class AlternatePrimaryKeyModel < ActiveRecord::Base self.primary_key = :my_id extend Connections attr_accessor :my_id end rspec-rails-2.13.2/spec/support/helpers.rb000066400000000000000000000010101214604200000204350ustar00rootroot00000000000000module Helpers def stub_metadata(additional_metadata) stub_metadata = metadata_with(additional_metadata) RSpec::Core::ExampleGroup.stub(:metadata) { stub_metadata } end def metadata_with(additional_metadata) m = RSpec::Core::Metadata.new m.process("example group") group_metadata = additional_metadata.delete(:example_group) if group_metadata m[:example_group].merge!(group_metadata) end m.merge!(additional_metadata) m end RSpec.configure {|c| c.include self} end rspec-rails-2.13.2/spec/support/matchers.rb000066400000000000000000000004141214604200000206100ustar00rootroot00000000000000RSpec::Matchers::define :be_included_in_files_in do |path| match do |mod| stub_metadata( :example_group => {:file_path => "#{path}whatever_spec.rb:15"} ) group = RSpec::Core::ExampleGroup.describe group.included_modules.include?(mod) end end rspec-rails-2.13.2/spec/support/null_object.rb000066400000000000000000000001201214604200000212740ustar00rootroot00000000000000class NullObject private def method_missing(method, *args, &blk) end end rspec-rails-2.13.2/templates/000077500000000000000000000000001214604200000160065ustar00rootroot00000000000000rspec-rails-2.13.2/templates/generate_stuff.rb000066400000000000000000000013541214604200000213370ustar00rootroot00000000000000generate('rspec:install') generate('controller wombats index') # plural generate('controller welcome index') # singular generate('integration_test widgets') generate('mailer Notifications signup') generate('model thing name:string') generate('helper things') generate('scaffold widget name:string category:string instock:boolean foo_id:integer bar_id:integer --force') generate('observer widget') generate('scaffold gadget') # scaffold with no attributes generate('scaffold admin/account name:string') # scaffold with nested resource generate('controller things custom_action') file "app/views/things/custom_action.html.erb", "This is a template for a custom action.", {:force=>true} run('rake db:migrate') run('rake db:migrate RAILS_ENV=test') rspec-rails-2.13.2/templates/run_specs.rb000066400000000000000000000006051214604200000203350ustar00rootroot00000000000000run('rspec spec -cfdoc') || abort run('rake --backtrace spec') || abort run('rake --backtrace spec:requests') || abort run('rake --backtrace spec:models') || abort run('rake --backtrace spec:views') || abort run('rake --backtrace spec:controllers') || abort run('rake --backtrace spec:helpers') || abort run('rake --backtrace spec:mailers') || abort run("rake --backtrace stats") || abort rspec-rails-2.13.2/yard/000077500000000000000000000000001214604200000147475ustar00rootroot00000000000000rspec-rails-2.13.2/yard/template/000077500000000000000000000000001214604200000165625ustar00rootroot00000000000000rspec-rails-2.13.2/yard/template/default/000077500000000000000000000000001214604200000202065ustar00rootroot00000000000000rspec-rails-2.13.2/yard/template/default/fulldoc/000077500000000000000000000000001214604200000216365ustar00rootroot00000000000000rspec-rails-2.13.2/yard/template/default/fulldoc/html/000077500000000000000000000000001214604200000226025ustar00rootroot00000000000000rspec-rails-2.13.2/yard/template/default/fulldoc/html/css/000077500000000000000000000000001214604200000233725ustar00rootroot00000000000000rspec-rails-2.13.2/yard/template/default/fulldoc/html/css/rspec.css000066400000000000000000000004011214604200000252130ustar00rootroot00000000000000.notetag { background-color: #FFE5E5; } code { background-color: #F0F0F0; padding: 0 2px 0 2px; } .deprecated code { background-color: #FFA8A8; } .summary_desc code { background-color: #F0F0F0; } .notetag code { background-color: #FFA8A8; } rspec-rails-2.13.2/yard/template/default/layout/000077500000000000000000000000001214604200000215235ustar00rootroot00000000000000rspec-rails-2.13.2/yard/template/default/layout/html/000077500000000000000000000000001214604200000224675ustar00rootroot00000000000000rspec-rails-2.13.2/yard/template/default/layout/html/setup.rb000066400000000000000000000003131214604200000241510ustar00rootroot00000000000000# Docs suggest I don't need this, but ... YARD::Server::Commands::StaticFileCommand::STATIC_PATHS << File.expand_path("../../../fulldoc/html/", __FILE__) def stylesheets super + ['css/rspec.css'] end