pax_global_header00006660000000000000000000000064132045174650014521gustar00rootroot0000000000000052 comment=68cea15c2d25f00fe453230502a06bda1a74c803 rspec-rails-3.7.2/000077500000000000000000000000001320451746500137565ustar00rootroot00000000000000rspec-rails-3.7.2/.document000066400000000000000000000000601320451746500155710ustar00rootroot00000000000000lib/**/*.rb - README.md LICENSE.md Changelog.md rspec-rails-3.7.2/.gitignore000066400000000000000000000003561320451746500157520ustar00rootroot00000000000000tmp doc pkg vendor !lib/rspec/rails/vendor *.gem Gemfile.lock bin .rvmrc *.rbc .yardoc .bundle .rails-version* .DS_Store Gemfile-custom .rbenv-version .rbx /.ruby-gemset /.ruby-version bundle .bundle specs.out spec/examples.txt specs.out rspec-rails-3.7.2/.rspec000066400000000000000000000000511320451746500150670ustar00rootroot00000000000000--warnings --color --require spec_helper rspec-rails-3.7.2/.rubocop.yml000066400000000000000000000026171320451746500162360ustar00rootroot00000000000000inherit_from: .rubocop_rspec_base.yml # Over time we'd like to get this down, but this is what we're at now. LineLength: Max: 186 # Over time we'd like to get this down, but this is what we're at now. MethodLength: Max: 50 # We use spaces, so it's less of a change to stick with that. SpaceAroundEqualsInParameterDefault: EnforcedStyle: space ################################################################################ # Individual File Exclusions ################################################################################ AllCops: Exclude: # Templates are really ERB which Rubocop does not parse - 'lib/generators/rspec/*/templates/**/*' FileName: Exclude: # We break convention here so that when bundler requires the gem, which # uses the gem name, things work without user configuration. - lib/rspec-rails.rb HandleExceptions: Exclude: # RSpec is tightly coupled to capybara right now, this should be # re-evaluted in the future. For now we allow the empty rescue - lib/rspec/rails/vendor/capybara.rb IfUnlessModifier: Exclude: # Allow single line statement as the style matches the remainder of the file - lib/rspec/rails/vendor/capybara.rb PerlBackrefs: Exclude: # We probably can refactor the backref out, but for now excluding it since # we can't use named matches in 1.8.7 - lib/generators/rspec/scaffold/scaffold_generator.rb rspec-rails-3.7.2/.rubocop_rspec_base.yml000066400000000000000000000070521320451746500204220ustar00rootroot00000000000000# This file was generated on 2017-09-15T10:18:21+09:00 from the rspec-dev repo. # DO NOT modify it by hand as your changes will get lost the next time it is generated. # This file contains defaults for RSpec projects. Individual projects # can customize by inheriting this file and overriding particular settings. AccessModifierIndentation: EnforcedStyle: outdent # "Use alias_method instead of alias" # We're fine with `alias`. Alias: Enabled: false AlignParameters: EnforcedStyle: with_first_parameter # "Avoid the use of the case equality operator ===" # We prefer using `Class#===` over `Object#is_a?` because `Class#===` # is less likely to be monkey patched than `is_a?` on a user object. CaseEquality: Enabled: false # Warns when the class is excessively long. ClassLength: Max: 100 CollectionMethods: PreferredMethods: reduce: 'inject' # Over time we'd like to get this down, but this is what we're at now. CyclomaticComplexity: Max: 10 # We use YARD to enforce documentation. It works better than rubocop's # enforcement...rubocop complains about the places we re-open # `RSpec::Expectations` and `RSpec::Matchers` w/o having doc commments. Documentation: Enabled: false # We still support 1.8.7 which requires trailing dots DotPosition: EnforcedStyle: trailing DoubleNegation: Enabled: false # each_with_object is unavailable on 1.8.7 so we have to disable this one. EachWithObject: Enabled: false Encoding: EnforcedStyle: when_needed FormatString: EnforcedStyle: percent # As long as we support ruby 1.8.7 we have to use hash rockets. HashSyntax: EnforcedStyle: hash_rockets # We can't use the new lambda syntax, since we still support 1.8.7. Lambda: Enabled: false # Over time we'd like to get this down, but this is what we're at now. LineLength: Max: 100 # Over time we'd like to get this down, but this is what we're at now. MethodLength: Max: 15 # Who cares what we call the argument for binary operator methods? OpMethod: Enabled: false PercentLiteralDelimiters: PreferredDelimiters: '%': () # double-quoted string '%i': '[]' # array of symbols '%q': () # single-quoted string '%Q': () # double-quoted string '%r': '{}' # regular expression pattern '%s': () # a symbol '%w': '[]' # array of single-quoted strings '%W': '[]' # array of double-quoted strings '%x': () # a shell command as a string # We have too many special cases where we allow generator methods or prefer a # prefixed predicate due to it's improved readability. PredicateName: Enabled: false # On 1.8 `proc` is `lambda`, so we use `Proc.new` to ensure we get real procs on all supported versions. # http://batsov.com/articles/2014/02/04/the-elements-of-style-in-ruby-number-12-proc-vs-proc-dot-new/ Proc: Enabled: false RedundantReturn: AllowMultipleReturnValues: true # Exceptions should be rescued with `Support::AllExceptionsExceptOnesWeMustNotRescue` RescueException: Enabled: true # We haven't adopted the `fail` to signal exceptions vs `raise` for re-raises convention. SignalException: Enabled: false # We've tended to use no space, so it's less of a change to stick with that. SpaceAroundEqualsInParameterDefault: EnforcedStyle: no_space # We don't care about single vs double qoutes. StringLiterals: Enabled: false # This rule favors constant names from the English standard library which we don't load. Style/SpecialGlobalVars: Enabled: false Style/TrailingComma: Enabled: false TrivialAccessors: AllowDSLWriters: true AllowPredicates: true ExactNameMatch: true rspec-rails-3.7.2/.travis.yml000066400000000000000000000077221320451746500160770ustar00rootroot00000000000000language: ruby sudo: false # We deviate from the rspec-dev cache setting here. # # Travis has special bundler support where it knows to run `bundle clean` # before backing up the bundle so it doesn't grow indefinitely. # # For the other repos we changed to specifying the directory specifically to # avoid the `bundle clean` travis was doing, because Myron found that, when # running one of the a build for one repo, the "run the rspec-core and # rspec-rails spec suites" parts would take a while because it would _always_ # have to install fresh gems (they weren't in the cache). This was happening # because travis was running `bundle clean` (due to the previous `cache: # bundler` config) against one repo which was was pruning gems installed for # the other repos. # # In our case, we aren't running the spec suites for the other repos so the # original `cache: bundler` is a better option. cache: bundler bundler_args: "--binstubs --path ../bundle --retry=3 --jobs=3" before_install: - script/clone_all_rspec_repos - gem update bundler before_script: # Rails 4.x complains with a bundler rails binstub in PROJECT_ROOT/bin/ - rm -f bin/rails - bundle exec rails --version script: "script/run_build 2>&1" rvm: - 1.8.7 - 2.4.2 - 2.3.5 - 2.2 - 2.1 - 2.0.0 - 1.9.3 - 1.9.2 env: - RAILS_VERSION='~> 4.2.0' - RAILS_VERSION=4-2-stable - RAILS_VERSION='~> 4.1.0' - RAILS_VERSION=4-1-stable - RAILS_VERSION='~> 4.0.4' - RAILS_VERSION=4-0-stable - RAILS_VERSION='~> 3.2.17' - RAILS_VERSION=3-2-stable - RAILS_VERSION='~> 3.1.12' - RAILS_VERSION='~> 3.0.20' matrix: include: # Rails 5.x only supports 2.2+ - rvm: 2.2.2 env: RAILS_VERSION=master - rvm: 2.2.2 env: RAILS_VERSION=5-0-stable - rvm: 2.2.2 env: RAILS_VERSION=5.1.0 - rvm: 2.3.5 env: RAILS_VERSION=master - rvm: 2.3.5 env: RAILS_VERSION=5-0-stable - rvm: 2.3.5 env: RAILS_VERSION=5.1.0 - rvm: 2.4.2 env: RAILS_VERSION=master - rvm: 2.4.2 env: RAILS_VERSION=5-0-stable - rvm: 2.4.2 env: RAILS_VERSION=5.1.0 exclude: # 3.0.x is not supported on MRI 2.0+ - rvm: 2.0.0 env: RAILS_VERSION='~> 3.0.20' - rvm: 2.1 env: RAILS_VERSION='~> 3.0.20' - rvm: 2.2 env: RAILS_VERSION='~> 3.0.20' - rvm: 2.3.5 env: RAILS_VERSION='~> 3.0.20' - rvm: 2.4.2 env: RAILS_VERSION='~> 3.0.20' # 4.x is not supported on MRI ruby-1.8.7 or 1.9.2 - rvm: 1.8.7 env: RAILS_VERSION='~> 4.0.4' - rvm: 1.9.2 env: RAILS_VERSION='~> 4.0.4' - 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.1.0' - rvm: 1.9.2 env: RAILS_VERSION='~> 4.1.0' - rvm: 1.8.7 env: RAILS_VERSION=4-1-stable - rvm: 1.9.2 env: RAILS_VERSION=4-1-stable - rvm: 1.8.7 env: RAILS_VERSION='~> 4.2.0' - rvm: 1.9.2 env: RAILS_VERSION='~> 4.2.0' - rvm: 1.8.7 env: RAILS_VERSION=4-2-stable - rvm: 1.9.2 env: RAILS_VERSION=4-2-stable # MRI 2.2+ is not supported on a few versions - rvm: 2.2 env: RAILS_VERSION='~> 3.1.12' - rvm: 2.3.5 env: RAILS_VERSION='~> 3.1.12' # MRI 2.4+ is not supported on a few versions - rvm: 2.4.2 env: RAILS_VERSION='~> 4.1.0' - rvm: 2.4.2 env: RAILS_VERSION=4-1-stable - rvm: 2.4.2 env: RAILS_VERSION='~> 4.0.4' - rvm: 2.4.2 env: RAILS_VERSION=4-0-stable - rvm: 2.4.2 env: RAILS_VERSION='~> 3.2.17' - rvm: 2.4.2 env: RAILS_VERSION=3-2-stable - rvm: 2.4.2 env: RAILS_VERSION='~> 3.1.12' allow_failures: - rvm: 2.2.2 env: RAILS_VERSION=master - rvm: 2.3.5 env: RAILS_VERSION=master - rvm: 2.4.2 env: RAILS_VERSION=master - rvm: 2.4.2 env: RAILS_VERSION='~> 4.2.0' - rvm: 2.4.2 env: RAILS_VERSION=4-2-stable fast_finish: true branches: only: - master - /^\d+-\d+-maintenance$/ rspec-rails-3.7.2/.yardopts000066400000000000000000000004201320451746500156200ustar00rootroot00000000000000--no-private --exclude features --exclude lib/generators/([^/]+/)*.*_spec.rb --exclude lib/generators/([^/]+/)*templates/([^/]+/)*.rb --exclude lib/generators/([^/]+/)*templates/.+\.rb --markup markdown --template-path yard/template/ - Changelog.md LICENSE.md Capybara.md rspec-rails-3.7.2/BUILD_DETAIL.md000066400000000000000000000124331320451746500161640ustar00rootroot00000000000000 # The CI build, in detail The [Travis CI build](https://travis-ci.org/rspec/rspec-rails) runs many verification steps to prevent regressions and ensure high-quality code. To run the Travis build locally, run: ``` $ script/run_build ``` It can be useful to run the build steps individually to repro a failing part of a Travis build. Let's break the build down into the individual steps. ## Specs RSpec dogfoods itself. Its primary defense against regressions is its spec suite. Run with: ``` $ bundle exec rspec # or, if you installed your bundle with `--standalone --binstubs`: $ bin/rspec ``` The spec suite performs a couple extra checks that are worth noting: * *That all the code is warning-free.* Any individual example that produces output to `stderr` will fail. We also have a spec that loads all the `lib` and `spec` files in a newly spawned process to detect load-time warnings and fail if there are any. RSpec must be warning-free so that users who enable Ruby warnings will not get warnings from our code. * *That only a minimal set of stdlibs are loaded.* Since Ruby makes loaded libraries available for use in any context, we want to minimize how many bits of the standard library we load and use. Otherwise, RSpec's use of part of the standard library could mask a problem where a gem author forgets to load a part of the standard library they rely on. The spec suite contains a spec that defines a whitelist of allowed loaded stdlibs. In addition, we use [SimpleCov](https://github.com/colszowka/simplecov) to measure and enforce test coverage. If the coverage falls below a project-specific threshold, the build will fail. ## Cukes RSpec uses [cucumber](https://cucumber.io/) for both acceptance testing and [documentation](https://relishapp.com/rspec). Since we publish our cukes as documentation, please limit new cucumber scenarios to user-facing examples that help demonstrate usage. Any tests that exist purely to prevent regressions should be written as specs, even if they are written in an acceptance style. Duplication between our YARD API docs and the cucumber documentation is fine. Run with: ``` $ bundle exec cucumber # or, if you installed your bundle with `--standalone --binstubs`: $ bin/cucumber ``` ## YARD documentation RSpec uses [YARD](http://yardoc.org/) for API documentation on the [rspec.info site](http://rspec.info/). Our commitment to [SemVer](htp://semver.org) requires that we explicitly declare our public API, and our build uses YARD to ensure that every class, module and method has either been labeled `@private` or has at least some level of documentation. For new APIs, this forces us to make an intentional decision about whether or not it should be part of RSpec's public API or not. To run the YARD documentation coverage check, run: ``` $ bundle exec yard stats --list-undoc # or, if you installed your bundle with `--standalone --binstubs`: $ bin/yard stats --list-undoc ``` We also want to prevent YARD errors or warnings when actually generating the docs. To check for those, run: ``` $ bundle exec yard doc --no-cache # or, if you installed your bundle with `--standalone --binstubs`: $ bin/yard doc --no-cache ``` ## Rubocop We use [Rubocop](https://github.com/bbatsov/rubocop) to enforce style conventions on the project so that the code has stylistic consistency throughout. Run with: ``` $ bundle exec rubocop lib # or, if you installed your bundle with `--standalone --binstubs`: $ bin/rubocop lib ``` Our Rubocop configuration is a work-in-progress, so if you get a failure due to a Rubocop default, feel free to ask about changing the configuration. Otherwise, you'll need to address the Rubocop failure, or, as a measure of last resort, by wrapping the offending code in comments like `# rubocop:disable SomeCheck` and `# rubocop:enable SomeCheck`. ## Run spec files one-by-one A fast TDD cycle depends upon being able to run a single spec file, without the rest of the test suite. While rare, it's fairly easy to create a situation where a spec passes when the entire suite runs but fails when its individual file is run. To guard against this, our CI build runs each spec file individually, using a bit of bash like: ``` for file in `find spec -iname '*_spec.rb'`; do echo "Running $file" bin/rspec $file -b --format progress done ``` Since this step boots RSpec so many times, it runs much, much faster when we can avoid the overhead of bundler. This is a main reason our CI build installs the bundle with `--standalone --binstubs` and runs RSpec via `bin/rspec` rather than `bundle exec rspec`. ## Running the spec suite for each of the other repos While each of the RSpec repos is an independent gem (generally designed to be usable on its own), there are interdependencies between the gems, and the specs for each tend to use features from the other gems. We don't want to merge a pull request for one repo that might break the build for another repo, so our CI build includes a spec that runs the spec suite of each of the _other_ project repos. Note that we only run the spec suite, not the full build, of the other projects, as the spec suite runs very quickly compared to the full build. rspec-rails-3.7.2/CODE_OF_CONDUCT.md000066400000000000000000000054401320451746500165600ustar00rootroot00000000000000 # Contributor Code of Conduct For the purpose of building a welcoming, harassment-free community that values contributions from anyone, the RSpec project has adopted the following code of conduct. All contributors and participants (including maintainers!) are expected to abide by its terms. As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery * Personal attacks * Trolling or insulting/derogatory comments * Public or private harassment * Publishing other's private information, such as physical or electronic addresses, without explicit permission * Other unethical or unprofessional conduct Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting one of the project maintainers listed at http://rspec.info/about/. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.3.0, available at [http://contributor-covenant.org/version/1/3/0/][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/3/0/ rspec-rails-3.7.2/CONTRIBUTING.md000066400000000000000000000030461320451746500162120ustar00rootroot00000000000000 # Contributing RSpec is a community-driven project that has benefited from improvements from over *500* contributors. We welcome contributions from *everyone*. While contributing, please follow the project [code of conduct](CODE_OF_CONDUCT.md), so that everyone can be included. If you'd like to help make RSpec better, here are some ways you can contribute: - by running RSpec HEAD to help us catch bugs before new releases - by [reporting bugs you encounter](https://github.com/rspec/rspec-rails/issues/new) - by [suggesting new features](https://github.com/rspec/rspec-rails/issues/new) - by improving RSpec's [Relish](https://relishapp.com/rspec) or [API](http://rspec.info/documentation/) documentation - by improving [RSpec's website](http://rspec.info/) ([source](https://github.com/rspec/rspec.github.io)) - by taking part in [feature and issue discussions](https://github.com/rspec/rspec-rails/issues) - by adding a failing test for reproducible [reported bugs](https://github.com/rspec/rspec-rails/issues) - by reviewing [pull requests](https://github.com/rspec/rspec-rails/pulls) and suggesting improvements - by [writing code](DEVELOPMENT.md) (no patch is too small! fix typos or bad whitespace) If you need help getting started, check out the [DEVELOPMENT](DEVELOPMENT.md) file for steps that will get you up and running. Thanks for helping us make RSpec better! rspec-rails-3.7.2/Capybara.md000066400000000000000000000041751320451746500160310ustar00rootroot00000000000000rspec-rails supports integration with Capybara 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, :file_path => "spec/requests" end rspec-rails-3.7.2/Changelog.md000066400000000000000000001041461320451746500161750ustar00rootroot00000000000000### Development [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.7.2...master) ### 3.7.2 / 2017-11-20 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.7.1...v3.7.2) Bug Fixes: * Delay loading system test integration until used. (Jon Rowe, #1903) * Ensure specs using the aggregate failures feature take screenshots on failure. (Matt Brictson, #1907) ### 3.7.1 / 2017-10-18 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.7.0...v3.7.1) Bug Fixes: * Prevent system test integration loading when puma or capybara are missing (Sam Phippen, #1884) ### 3.7.0 / 2017-10-17 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.6.0...v3.7.0) Bug Fixes: * Prevent "template not rendered" log message from erroring in threaded environments. (Samuel Cochran, #1831) * Correctly generate job name in error message. (Wojciech Wnętrzak, #1814) Enhancements: * Allow `be_a_new(...).with(...)` matcher to accept matchers for attribute values. (Britni Alexander, #1811) * Only configure RSpec Mocks if it is fully loaded. (James Adam, #1856) * Integrate with `ActionDispatch::SystemTestCase`. (Sam Phippen, #1813) ### 3.6.0 / 2017-05-04 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.6.0.beta2...v3.6.0) Enhancements: * Add compatibility for Rails 5.1. (Sam Phippen, Yuichiro Kaneko, #1790) Bug Fixes: * Fix scaffold generator so that it does not generate broken controller specs on Rails 3.x and 4.x. (Yuji Nakayama, #1710) ### 3.6.0.beta2 / 2016-12-12 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.6.0.beta1...v3.6.0.beta2) Enhancements: * Improve failure output of ActiveJob matchers by listing queued jobs. (Wojciech Wnętrzak, #1722) * Load `spec_helper.rb` earlier in `rails_helper.rb` by default. (Kevin Glowacz, #1795) ### 3.6.0.beta1 / 2016-10-09 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.5.2...v3.6.0.beta1) Enhancements: * Add support for `rake notes` in Rails `>= 5.1`. (John Meehan, #1661) * Remove `assigns` and `assert_template` from scaffold spec generators (Josh Justice, #1689) * Add support for generating scaffolds for api app specs. (Krzysztof Zych, #1685) ### 3.5.2 / 2016-08-26 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.5.1...v3.5.2) Bug Fixes: * Stop unnecessarily loading `rspec/core` from `rspec/rails` to avoid IRB context warning. (Myron Marston, #1678) * Deserialize arguments within ActiveJob matchers correctly. (Wojciech Wnętrzak, #1684) ### 3.5.1 / 2016-07-08 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.5.0...v3.5.1) Bug Fixes: * Only attempt to load `ActionDispatch::IntegrationTest::Behavior` on Rails 5, and above; Prevents possible `TypeError` when an existing `Behaviour` class is defined. (#1660, Betesh). ### 3.5.0 / 2016-07-01 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.5.0.beta4...v3.5.0) **No user facing changes since beta4** ### 3.5.0.beta4 / 2016-06-05 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.5.0.beta3...v3.5.0.beta4) Enhancements: * Add support for block when using `with` on `have_enqueued_job`. (John Schroeder, #1578) * Add support for `file_fixture(...)`. (Wojciech Wnętrzak, #1587) * Add support for `setup` and `teardown` with blocks (Miklós Fazekas, #1598) * Add `enqueue_job ` alias for `have_enqueued_job`, support `once`/`twice`/ `thrice`, add `have_been_enqueued` matcher to support use without blocks. (Sergey Alexandrovich, #1613) Bug fixes: * Prevent asset helpers from taking precendence over route helpers. (Prem Sichanugrist, #1496) * Prevent `NoMethodError` during failed `have_rendered` assertions on weird templates. (Jon Rowe, #1623). ### 3.5.0.beta3 / 2016-04-02 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.5.0.beta2...v3.5.0.beta3) Enhancements: * Add support for Rails 5 Beta 3 (Sam Phippen, Benjamin Quorning, Koen Punt, #1589, #1573) Bug fixes: * Support custom resolvers when preventing views from rendering. (Jon Rowe, Benjamin Quorning, #1580) ### 3.5.0.beta2 / 2016-03-10 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.5.0.beta1...v3.5.0.beta2) Enhancements: * Include `ActionDispatch::IntegrationTest::Behavior` in request spec example groups when on Rails 5, allowing integration test helpers to be used in request specs. (Scott Bronson, #1560) Bug fixes: * Make it possible to use floats in auto generated (scaffold) tests. (Alwahsh, #1550) ### 3.5.0.beta1 / 2016-02-06 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.4.2...v3.5.0.beta1) Enhancements: * Add a `--singularize` option for the feature spec generator (Felicity McCabe, #1503) * Prevent leaking TestUnit methods in Rails 4+ (Fernando Seror Garcia, #1512) * Add support for Rails 5 (Sam Phippen, #1492) Bug fixes: * Make it possible to write nested specs within helper specs on classes that are internal to helper classes. (Sam Phippen, Peter Swan, #1499). * Warn if a fixture method is called from a `before(:context)` block, instead of crashing with a `undefined method for nil:NilClass`. (Sam Phippen, #1501) * Expose path to view specs (Ryan Clark, Sarah Mei, Sam Phippen, #1402) * Prevent installing Rails 3.2.22.1 on Ruby 1.8.7. (Jon Rowe, #1540) * Raise a clear error when `have_enqueued_job` is used with non-test adapter. (Wojciech Wnętrzak, #1489) ### 3.4.2 / 2016-02-02 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.4.1...v3.4.2) Bug Fixes: * Cache template resolvers during path lookup to prevent performance regression from #1535. (Andrew White, #1544) ### 3.4.1 / 2016-01-25 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.4.0...v3.4.1) Bug Fixes: * Fix no method error when rendering templates with explicit `:file` parameters for Rails version `4.2.5.1`. (Andrew White, Sam Phippen, #1535) ### 3.4.0 / 2015-11-11 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.3.3...v3.4.0) Enhancements: * Improved the failure message for `have_rendered` matcher on a redirect response. (Alex Egan, #1440) * Add configuration option to filter out Rails gems from backtraces. (Bradley Schaefer, #1458) * Enable resolver cache for view specs for a large speed improvement (Chris Zetter, #1452) * Add `have_enqueued_job` matcher for checking if a block has queued jobs. (Wojciech Wnętrzak, #1464) Bug Fixes: * Fix another load order issued which causes an undefined method `fixture_path` error when loading rspec-rails after a spec has been created. (Nikki Murray, #1430) * Removed incorrect surrounding whitespace in the rspec-rails backtrace exclusion pattern for its own `lib` code. (Jam Black, #1439) ### 3.3.3 / 2015-07-15 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.3.2...v3.3.3) Bug Fixes: * Fix issue with generators caused by `Rails.configuration.hidden_namespaces` including symbols. (Dan Kohn, #1414) ### 3.3.2 / 2015-06-18 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.3.1...v3.3.2) Bug Fixes: * Fix regression that caused stubbing abstract ActiveRecord model classes to trigger internal errors in rails due the the verifying double lifecycle wrongly calling `define_attribute_methods` on the abstract AR class. (Jon Rowe, #1396) ### 3.3.1 / 2015-06-14 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.3.0...v3.3.1) Bug Fixes: * Fix regression that caused stubbing ActiveRecord model classes to trigger internal errors in rails. (Myron Marston, Aaron Kromer, #1395) ### 3.3.0 / 2015-06-12 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.2.3...v3.3.0) Enhancements: * Add support for PATCH to route specs created via scaffold. (Igor Zubkov, #1336) * Improve controller and routing spec calls to `routes` by using `yield` instead of `call`. (Anton Davydov, #1308) * Add support for `ActiveJob` specs as standard `RSpec::Rails::RailsExampleGoup`s via both `:type => :job` and inferring type from spec directory `spec/jobs`. (Gabe Martin-Dempesy, #1361) * Include `RSpec::Rails::FixtureSupport` into example groups using metadata `:use_fixtures => true`. (Aaron Kromer, #1372) * Include `rspec:request` generator for generating request specs; this is an alias of `rspec:integration` (Aaron Kromer, #1378) * Update `rails_helper` generator with a default check to abort the spec run when the Rails environment is production. (Aaron Kromer, #1383) ### 3.2.3 / 2015-06-06 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.2.2...v3.2.3) Bug Fixes: * Fix regression with the railtie resulting in undefined method `preview_path=` on Rails 3.x and 4.0 (Aaron Kromer, #1388) ### 3.2.2 / 2015-06-03 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.2.1...v3.2.2) Bug Fixes: * Fix auto-including of generic `Helper` object for view specs sitting in the `app/views` root (David Daniell, #1289) * Remove pre-loading of ActionMailer in the Railtie (Aaron Kromer, #1327) * Fix undefined method `need_auto_run=` error when using Ruby 2.1 and Rails 3.2 without the test-unit gem (Orien Madgwick, #1350) * Fix load order issued which causes an undefined method `fixture_path` error when loading rspec-rails after a spec has been created. (Aaron Kromer, #1372) ### 3.2.1 / 2015-02-23 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.2.0...v3.2.1) Bug Fixes: * Add missing `require` to RSpec generator root fixing an issue where Rail's autoload does not find it in some environments. (Aaron Kromer, #1305) * `be_routable` matcher now has the correct description. (Tony Ta, #1310) * Fix dependency to allow Rails 4.2.x patches / pre-releases (Lucas Mazza, #1318) * Disable the `test-unit` gem's autorunner on projects running Rails < 4.1 and Ruby < 2.2 (Aaron Kromer, #1320) ### 3.2.0 / 2015-02-03 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.1.0...v3.2.0) Enhancements: * Include generator for `ActionMailer` mailer previews (Takashi Nakagawa, #1185) * Configure the `ActionMailer` preview path via a Railtie (Aaron Kromer, #1236) * Show all RSpec generators when running `rails generate` (Eliot Sykes, #1248) * Support Ruby 2.2 with Rails 3.2 and 4.x (Aaron Kromer, #1264, #1277) * Improve `instance_double` to support verifying dynamic column methods defined by `ActiveRecord` (Jon Rowe, #1238) * Mirror the use of Ruby 1.9 hash syntax for the `type` tags in the spec generators on Rails 4. (Michael Stock, #1292) Bug Fixes: * Fix `rspec:feature` generator to use `RSpec` namespace preventing errors when monkey-patching is disabled. (Rebecca Skinner, #1231) * Fix `NoMethodError` caused by calling `RSpec.feature` when Capybara is not available or the Capybara version is < 2.4.0. (Aaron Kromer, #1261) * Fix `ArgumentError` when using an anonymous controller which inherits an outer group's anonymous controller. (Yuji Nakayama, #1260) * Fix "Test is not a class (TypeError)" error when using a custom `Test` class in Rails 4.1 and 4.2. (Aaron Kromer, #1295) ### 3.1.0 / 2014-09-04 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.0.2...v3.1.0) Enhancements: * Switch to using the `have_http_status` matcher in spec generators. (Aaron Kromer, #1086) * Update `rails_helper` generator to allow users to opt-in to auto-loading `spec/support` files instead of forcing it upon them. (Aaron Kromer, #1137) * Include generator for `ActiveJob`. (Abdelkader Boudih, #1155) * Improve support for non-ActiveRecord apps by not loading ActiveRecord related settings in the generated `rails_helper`. (Aaron Kromer, #1150) * Remove Ruby warnings as a suggested configuration. (Aaron Kromer, #1163) * Improve the semantics of the controller spec for scaffolds. (Griffin Smith, #1204) * Use `#method` syntax in all generated controller specs. (Griffin Smith, #1206) Bug Fixes: * Fix controller route lookup for Rails 4.2. (Tomohiro Hashidate, #1142) ### 3.0.2 / 2014-07-21 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.0.1...v3.0.2) Bug Fixes: * Suppress warning in `SetupAndTeardownAdapter`. (André Arko, #1085) * Remove dependency on Rubygems. (Andre Arko & Doc Riteze, #1099) * Standardize controller spec template style. (Thomas Kriechbaumer, #1122) ### 3.0.1 / 2014-06-02 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.0.0...v3.0.1) Bug Fixes: * Fix missing require in `rails g rspec:install`. (Sam Phippen, #1058) ### 3.0.0 / 2014-06-01 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.0.0.rc1...v3.0.0) Enhancements: * Separate RSpec configuration in generated `spec_helper` from Rails setup and associated configuration options. Moving Rails specific settings and options to `rails_helper`. (Aaron Kromer) Bug Fixes: * Fix an issue with fixture support when `ActiveRecord` isn't loaded. (Jon Rowe) ### 3.0.0.rc1 / 2014-05-18 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.0.0.beta2...v3.0.0.rc1) Breaking Changes for 3.0.0: * Extracts the `mock_model` and `stub_model` methods to the `rspec-activemodel-mocks` gem. (Thomas Holmes) * Spec types are no longer inferred by location, they instead need to be explicitly tagged. The old behaviour is enabled by `config.infer_spec_type_from_file_location!`, which is still supplied in the default generated `spec_helper.rb`. (Xavier Shay, Myron Marston) * `controller` macro in controller specs no longer mutates `:described_class` metadata. It still overrides the subject and sets the controller, though. (Myron Marston) * Stop depending on or requiring `rspec-collection_matchers`. Users who want those matchers should add the gem to their Gemfile and require it themselves. (Myron Marston) * Removes runtime dependency on `ActiveModel`. (Rodrigo Rosenfeld Rosas) Enhancements: * Supports Rails 4.x reference attribute ids in generated scaffold for view specs. (Giovanni Cappellotto) * Add `have_http_status` matcher. (Aaron Kromer) * Add spec type metadata to generator templates. (Aaron Kromer) Bug Fixes: * Fix an inconsistency in the generated scaffold specs for a controller. (Andy Waite) * Ensure `config.before(:all, :type => )` hooks run before groups of the given type, even when the type is inferred by the file location. (Jon Rowe, Myron Marston) * Switch to parsing params with `Rack::Utils::parse_nested_query` to match Rails. (Tim Watson) * Fix incorrect namespacing of anonymous controller routes. (Aaron Kromer) ### 3.0.0.beta2 / 2014-02-17 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.0.0.beta1...v3.0.0.beta2) Breaking Changes for 3.0.0: * Removes the `--webrat` option for the request spec generator (Andy Lindeman) * Methods from `Capybara::DSL` (e.g., `visit`) are no longer available in controller specs. It is more appropriate to use capybara in feature specs (`spec/features`) instead. (Andy Lindeman) * `infer_base_class_for_anonymous_controllers` is enabled by default. (Thomas Holmes) * Capybara 2.2.0 or above is required for feature specs. (Andy Lindeman) Enhancements: * Improve `be_valid` matcher for non-ActiveModel::Errors implementations (Ben Hamill) Bug Fixes: * Use `__send__` rather than `send` to prevent naming collisions (Bradley Schaefer) * Supports Rails 4.1. (Andy Lindeman) * Routes are drawn correctly for anonymous controllers with abstract parents. (Billy Chan) * Loads ActiveSupport properly to support changes in Rails 4.1. (Andy Lindeman) * Anonymous controllers inherit from `ActionController::Base` if `ApplicationController` is not present. (Jon Rowe) * Require `rspec/collection_matchers` when `rspec/rails` is required. (Yuji Nakayama) ### 3.0.0.beta1 / 2013-11-07 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v2.99.0...v3.0.0.beta1) Breaking Changes for 3.0.0: * Extracts `autotest` and `autotest-rails` support to `rspec-autotest` gem. (Andy Lindeman) ### 2.99.0 / 2014-06-01 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v2.99.0.rc1...v2.99.0) No changes. Just taking it out of pre-release. ### 2.99.0.rc1 / 2014-05-18 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v2.99.0.beta2...v2.99.0.rc1) Deprecations * Deprecates `stub_model` and `mock_model` in favor of the `rspec-activemodel-mocks` gem. (Thomas Holmes) * Issue a deprecation to instruct users to configure `config.infer_spec_type_from_file_location!` during the upgrade process since spec type inference is opt-in in 3.0. (Jon Rowe) * Issue a deprecation when `described_class` is accessed in a controller example group that has used the `controller { }` macro to generate an anonymous controller class, since in 2.x, `described_class` would return that generated class but in 3.0 it will continue returning the class passed to `describe`. (Myron Marston) ### 2.99.0.beta2 / 2014-02-17 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v2.99.0.beta1...v2.99.0.beta2) Deprecations: * Deprecates the `--webrat` option to the scaffold and request spec generator (Andy Lindeman) * Deprecates the use of `Capybara::DSL` (e.g., `visit`) in controller specs. It is more appropriate to use capybara in feature specs (`spec/features`) instead. (Andy Lindeman) Bug Fixes: * Use `__send__` rather than `send` to prevent naming collisions (Bradley Schaefer) * Supports Rails 4.1. (Andy Lindeman) * Loads ActiveSupport properly to support changes in Rails 4.1. (Andy Lindeman) * Anonymous controllers inherit from `ActionController::Base` if `ApplicationController` is not present. (Jon Rowe) ### 2.99.0.beta1 / 2013-11-07 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v2.14.0...v2.99.0.beta1) Deprecations: * Deprecates autotest integration in favor of the `rspec-autotest` gem. (Andy Lindeman) Enhancements: * Supports Rails 4.1 and Minitest 5. (Patrick Van Stee) Bug Fixes: * Fixes "warning: instance variable @orig\_routes not initialized" raised by controller specs when `--warnings` are enabled. (Andy Lindeman) * Where possible, check against the version of ActiveRecord, rather than Rails. It is possible to use some of rspec-rails without all of Rails. (Darryl Pogue) * Explicitly depends on `activemodel`. This allows libraries that do not bring in all of `rails` to use `rspec-rails`. (John Firebaugh) ### 2.14.1 / 2013-12-29 [full changelog](http://github.com/rspec/rspec-rails/compare/v2.14.0...v2.14.1) Bug Fixes: * Fixes "warning: instance variable @orig\_routes not initialized" raised by controller specs when `--warnings` are enabled. (Andy Lindeman) * Where possible, check against the version of ActiveRecord, rather than Rails. It is possible to use some of rspec-rails without all of Rails. (Darryl Pogue) * Supports Rails 4.1 and Minitest 5. (Patrick Van Stee, Andy Lindeman) * Explicitly depends on `activemodel`. This allows libraries that do not bring in all of `rails` to use `rspec-rails`. (John Firebaugh) * Use `__send__` rather than `send` to prevent naming collisions (Bradley Schaefer) ### 2.14.0 / 2013-07-06 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v2.14.0.rc1...v2.14.0) Bug fixes * Rake tasks do not define methods that might interact with other libraries. (Fujimura Daisuke) * Reverts fix for out-of-order `let` definitions in controller specs after the issue was fixed upstream in rspec-core. (Andy Lindeman) * Fixes deprecation warning when using `expect(Model).to have(n).records` with Rails 4. (Andy Lindeman) ### 2.14.0.rc1 / 2013-05-27 [Full Changelog](http://github.com/rspec/rspec-rails/compare/v2.13.2...v2.14.0.rc1) Enhancements * Prelimiarily support Rails 4.1 by updating adapters to support Minitest 5.0. (Andy Lindeman) Bug fixes * `rake stats` runs correctly when spec files exist at the top level of the spec/ directory. (Benjamin Fleischer) ### 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) Enhancements * Document how the spec/support directory works. (Sam Phippen) ### 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-3.7.2/DEVELOPMENT.md000066400000000000000000000115151320451746500160650ustar00rootroot00000000000000 # Development Setup Generally speaking, you only need to clone the project and install the dependencies with [Bundler](http://bundler.io/). You can either get a full RSpec development environment using [rspec-dev](https://github.com/rspec/rspec-dev#README) or you can set this project up individually. ## Setting up rspec-rails individually For most contributors, setting up the project individually will be simpler. Unless you have a specific reason to use rspec-dev, we recommend using this approach. Clone the repo: ``` $ git clone git@github.com:rspec/rspec-rails.git ``` Install the dependencies using [Bundler](http://bundler.io/): ``` $ cd rspec-rails $ bundle install ``` To minimize boot time and to ensure we don't depend upon any extra dependencies loaded by Bundler, our CI builds avoid loading Bundler at runtime by using Bundler's [`--standalone option`](http://myronmars.to/n/dev-blog/2012/03/faster-test-boot-times-with-bundler-standalone). While not strictly necessary (many/most of our contributors do not do this!), if you want to exactly reproduce our CI builds you'll want to do the same: ``` $ bundle install --standalone --binstubs ``` The `--binstubs` option creates the `bin/rspec` file that, like `bundle exec rspec`, will load all the versions specified in `Gemfile.lock` without loading bundler at runtime! ## Using rspec-dev See the [rspec-dev README](https://github.com/rspec/rspec-dev#README) for setup instructions. The rspec-dev project contains many rake tasks for helping manage an RSpec development environment, making it easy to do things like: * Change branches across all repos * Update all repos with the latest code from `master` * Cut a new release across all repos * Push out updated build scripts to all repos These sorts of tasks are essential for the RSpec maintainers but will probably be unnecessary complexity if you're just contributing to one repository. If you are getting setup to make your first contribution, we recommend you take the simpler route of setting up rspec-rails individually. ## Gotcha: Version mismatch from sibling repos The [Gemfile](Gemfile) is designed to be flexible and support using the other RSpec repositories either from a local sibling directory (e.g. `../rspec-`) or, if there is no such directory, directly from git. This generally does the "right thing", but can be a gotcha in some situations. For example, if you are setting up `rspec-core`, and you happen to have an old clone of `rspec-expectations` in a sibling directory, it'll be used even though it might be months or years out of date, which can cause confusing failures. To avoid this problem, you can either `export USE_GIT_REPOS=1` to force the use of `:git` dependencies instead of local dependencies, or update the code in the sibling directory. rspec-dev contains rake tasks to help you keep all repos in sync. ## Extra Gems If you need additional gems for any tasks---such as `benchmark-ips` for benchmarking or `byebug` for debugging---you can create a `Gemfile-custom` file containing those gem declarations. The `Gemfile` evaluates that file if it exists, and it is git-ignored. # Running the build The [Travis CI build](https://travis-ci.org/rspec/rspec-rails) runs many verification steps to prevent regressions and ensure high-quality code. To run the Travis build locally, run: ``` $ script/run_build ``` See [build detail](BUILD_DETAIL.md) for more detail. # What to Expect To ensure high, uniform code quality, all code changes (including changes from the maintainers!) are subject to a pull request code review. We'll often ask for clarification or suggest alternate ways to do things. Our code reviews are intended to be a two-way conversation. Here's a short, non-exhaustive checklist of things we typically ask contributors to do before PRs are ready to merge. It can help get your PR merged faster if you do these in advance! - [ ] New behavior is covered by tests and all tests are passing. - [ ] No Ruby warnings are issued by your changes. - [ ] Documentation reflects changes and renders as intended. - [ ] Rubocop passes (e.g. `bundle exec rubocop lib`). - [ ] Commits are squashed into a reasonable number of logical changesets that tell an easy-to-follow story. - [ ] No changelog entry is necessary (we'll add it as part of the merge process!) # Adding Docs RSpec uses [YARD](http://yardoc.org/) for its API documentation. To ensure the docs render well, we recommend running a YARD server and viewing your edits in a browser. To run a YARD server: ``` $ bundle exec yard server --reload # or, if you installed your bundle with `--standalone --binstubs`: $ bin/yard server --reload ``` Then navigate to `localhost:8808` to view the rendered docs. rspec-rails-3.7.2/Gemfile000066400000000000000000000040321320451746500152500ustar00rootroot00000000000000source "https://rubygems.org" version_file = File.expand_path("../.rails-version", __FILE__) RAILS_VERSION = ENV['RAILS_VERSION'] || (File.exist?(version_file) && File.read(version_file).chomp) gemspec rspec_dependencies_gemfile = File.expand_path("../Gemfile-rspec-dependencies", __FILE__) eval_gemfile rspec_dependencies_gemfile gem 'yard', '~> 0.8.7', :require => false ### deps for rdoc.info group :documentation do gem 'redcarpet', '2.3.0' gem 'github-markup', '1.0.0' if RUBY_VERSION > '2.0.0' gem 'relish' end end platforms :jruby do gem "jruby-openssl" end gem 'sqlite3', '~> 1.3.6' if RUBY_VERSION >= '2.4.0' gem 'json', '>= 2.0.2' end if RUBY_VERSION >= '1.9.3' gem 'rake', '>= 10.0.0' else gem 'rake', '~> 10.0' # rake 11 requires Ruby 1.9.3 or later end # Version 3 of mime-types 3 requires Ruby 2.0 if RUBY_VERSION < '2.0.0' gem 'mime-types', '< 3' end # Capybara versions that support RSpec 3 only support RUBY_VERSION >= 1.9.3 if RUBY_VERSION >= '1.9.3' if /5(\.|-)1/ === RAILS_VERSION || "master" == RAILS_VERSION gem 'capybara', '~> 2.13', :require => false else gem 'capybara', '~> 2.2.0', :require => false end end # Rack::Cache 1.3.0 requires Ruby >= 2.0.0 gem 'rack-cache', '< 1.3.0' if RUBY_VERSION < '2.0.0' if RUBY_VERSION < '1.9.2' gem 'nokogiri', '~> 1.5.0' elsif RUBY_VERSION < '1.9.3' gem 'nokogiri', '1.5.2' else gem 'nokogiri', '1.6.7.1' end if RUBY_VERSION <= '1.8.7' # cucumber and gherkin require rubyzip as a runtime dependency on 1.8.7 # Only < 1.0 supports 1.8.7 gem 'rubyzip', '< 1.0' end if RUBY_VERSION >= '2.0.0' && RUBY_VERSION < '2.2.0' # our current rubocop version doesn't support the json version required by Ruby 2.4 # our rails rubocop setup only supports 2.0 and 2.1 gem 'rubocop', "~> 0.23.0" end custom_gemfile = File.expand_path("../Gemfile-custom", __FILE__) eval_gemfile custom_gemfile if File.exist?(custom_gemfile) rails_dependencies_gemfile = File.expand_path("../Gemfile-rails-dependencies", __FILE__) eval_gemfile rails_dependencies_gemfile rspec-rails-3.7.2/Gemfile-custom.sample000066400000000000000000000005441320451746500200440ustar00rootroot00000000000000group :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-3.7.2/Gemfile-rails-dependencies000066400000000000000000000042151320451746500210070ustar00rootroot00000000000000version_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 "web-console", :git => "git://github.com/rails/web-console", :group => :development gem 'sass-rails', :git => "git://github.com/rails/sass-rails.git" gem 'coffee-rails', :git => "git://github.com/rails/coffee-rails.git" gem 'rack', :git => 'git://github.com/rack/rack.git' gem 'i18n', :git => 'git://github.com/svenfuchs/i18n.git', :branch => 'master' gem 'sprockets', :git => 'git://github.com/rails/sprockets.git', :branch => 'master' gem 'sprockets-rails', :git => 'git://github.com/rails/sprockets-rails.git', :branch => 'master' if RUBY_VERSION >= "1.9.3" gem 'puma', :git => 'git://github.com/puma/puma', :branch => 'master' end when /stable$/ gem_list = %w[rails railties actionmailer actionpack activerecord activesupport] gem_list << 'activejob' if version > '4-1-stable' gem_list << 'actionview' if version > '4-0-stable' if RUBY_VERSION >= "1.9.3" gem_list << 'puma' if version > '5-0-stable' end gem_list.each do |rails_gem| gem rails_gem, :git => "git://github.com/rails/rails.git", :branch => version end when nil, false, "" if RUBY_VERSION < '1.9.3' # Rails 4+ requires 1.9.3+, so on earlier versions default to the last 3.x release. gem "rails", "~> 3.2.17" elsif RUBY_VERSION < '2.2.0' # Rails 5+ requires 2.2+, so on earlier versions default to the last 4.x release. gem "rails", "~> 4.2.0" else gem "rails", "~> 5.0.0" end else gem "rails", version if version >= '5-1-stable' && RUBY_VERSION >= "1.9.3" gem "puma" end end gem "i18n", '< 0.7.0' if RUBY_VERSION < '1.9.3' gem "test-unit" if RUBY_VERSION >= '2.2.0' && version =~ /3[.-]2[.-]/ rspec-rails-3.7.2/Gemfile-rspec-dependencies000066400000000000000000000006701320451746500210120ustar00rootroot00000000000000branch = File.read(File.expand_path("../maintenance-branch", __FILE__)).chomp %w[rspec rspec-core rspec-expectations rspec-mocks rspec-support].each do |lib| library_path = File.expand_path("../../#{lib}", __FILE__) if File.exist?(library_path) && !ENV['USE_GIT_REPOS'] gem lib, :path => library_path, :require => false else gem lib, :git => "git://github.com/rspec/#{lib}.git", :branch => branch, :require => false end end rspec-rails-3.7.2/LICENSE.md000066400000000000000000000023221320451746500153610ustar00rootroot00000000000000The MIT License (MIT) ===================== * Copyright © 2015 David Chelimsky, Aaron Kromer * Copyright © 2012 David Chelimsky, Andy Lindeman * Copyright © 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-3.7.2/README.md000066400000000000000000000436271320451746500152510ustar00rootroot00000000000000# rspec-rails [![Build Status](https://secure.travis-ci.org/rspec/rspec-rails.svg?branch=master)](http://travis-ci.org/rspec/rspec-rails) [![Code Climate](https://img.shields.io/codeclimate/github/rspec/rspec-rails.svg)](https://codeclimate.com/github/rspec/rspec-rails) **rspec-rails** is a testing framework for Rails 3.x, 4.x and 5.0. 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', '~> 3.6' end ``` Want to run against the `master` branch? You'll need to include the dependent RSpec repos as well. Add the following to your `Gemfile`: ```ruby %w[rspec-core rspec-expectations rspec-mocks rspec-rails rspec-support].each do |lib| gem lib, :git => "https://github.com/rspec/#{lib}.git", :branch => 'master' end ``` Download and install by running: ``` bundle install ``` Initialize the `spec/` directory (where specs will reside) with: ``` rails generate rspec:install ``` This adds the following files which are used for configuration: - `.rspec` - `spec/spec_helper.rb` - `spec/rails_helper.rb` Check the comments in each file for more information. Use the `rspec` command to run your specs: ``` bundle exec rspec ``` By default the above will run all `_spec.rb` files in the `spec` directory. For more details about this see the [RSpec spec file docs](https://www.relishapp.com/rspec/rspec-core/docs/spec-files). To run only a subset of these specs use the following command: ``` # Run only model specs bundle exec rspec spec/models # Run only specs for AccountsController bundle exec rspec spec/controllers/accounts_controller_spec.rb # Run only spec on line 8 of AccountsController bundle exec rspec spec/controllers/accounts_controller_spec.rb:8 ``` 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 ``` ### Upgrade Note For detailed information on the general RSpec 3.x upgrade process see the [RSpec Upgrade docs](https://relishapp.com/rspec/docs/upgrade). There are three particular `rspec-rails` specific changes to be aware of: 1. [The default helper files created in RSpec 3.x have changed](https://www.relishapp.com/rspec/rspec-rails/docs/upgrade#default-helper-files) 2. [File-type inference disabled by default](https://www.relishapp.com/rspec/rspec-rails/docs/upgrade#file-type-inference-disabled) 3. [Rails 4.x `ActiveRecord::Migration` pending migration checks](https://www.relishapp.com/rspec/rspec-rails/docs/upgrade#pending-migration-checks) 4. Extraction of `stub_model` and `mock_model` to [`rspec-activemodel-mocks`](https://github.com/rspec/rspec-activemodel-mocks) 5. In Rails 5.x, controller testing has been moved to its own gem which is [rails-controller-testing](https://github.com/rails/rails-controller-testing). Using `assigns` in your controller specs without adding this gem will no longer work. 6. `rspec-rails` now includes two helpers, `spec_helper.rb` and `rails_helper.rb`. `spec_helper.rb` is the conventional RSpec configuration helper, whilst the Rails specific loading and bootstrapping has moved to the `rails_helper.rb` file. Rails specs now need this file required beforehand either at the top of the specific file (recommended) or a common configuration location such as your `.rspec` file. Please see the [RSpec Rails Upgrade docs](https://www.relishapp.com/rspec/rspec-rails/docs/upgrade) for full details. **NOTE:** Generators run in RSpec 3.x will now require `rails_helper` instead of `spec_helper`. ### 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. You may also invoke RSpec generators independently. For instance, running `rails generate rspec:model` will generate a model spec. For more information, see [list of all generators](https://www.relishapp.com/rspec/rspec-rails/docs/generators). ## Contributing Once you've set up the environment, you'll need to cd into the working directory of whichever repo you want to work in. From there you can run the specs and cucumber features, and make patches. NOTE: You do not need to use rspec-dev to work on a specific RSpec repo. You can treat each RSpec repo as an independent project. Please see the following files: For `rspec-rails`-specific development information, see - [Build details](BUILD_DETAIL.md) - [Code of Conduct](CODE_OF_CONDUCT.md) - [Detailed contributing guide](CONTRIBUTING.md) - [Development setup guide](DEVELOPMENT.md) ## Model Specs Use model specs to describe behavior of models (usually ActiveRecord-based) in the application. Model specs default to residing in the `spec/models` folder. Tagging any context with the metadata `:type => :model` treats its examples as model specs. For example: ```ruby require "rails_helper" RSpec.describe User, :type => :model 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). ## Request Specs Use request specs to describe the client-facing behavior of the application — specifically, the HTTP response to be issued for a given request (a.k.a. integration tests). Since such client-facing behavior encompasses controller actions, this is the type of spec to use for controller testing. Request specs default to residing in the `spec/requests`, `spec/api`, and `spec/integration` directories. Tagging any context with the metadata `:type => :request` treats its examples as request specs. Request specs mix in behavior from [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). ```ruby require 'rails_helper' RSpec.describe "home page", :type => :request 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 ``` The above example uses only standard Rails and RSpec APIs, but many RSpec/Rails users like to use extension libraries like [FactoryBot](https://github.com/thoughtbot/factory_bot) and [Capybara](https://github.com/jnicklas/capybara): ```ruby require 'rails_helper' RSpec.describe "home page", :type => :request do it "displays the user's username after successful login" do user = FactoryBot.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 ``` FactoryBot 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 FactoryBot 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. For more information, see [cucumber scenarios for request specs](https://relishapp.com/rspec/rspec-rails/docs/request-specs/request-spec). ## Controller Specs Controller specs can be used to describe the behavior of Rails controllers. As of version 3.5, however, controller specs are discouraged in favor of request specs (which also focus largely on controllers, but capture other critical aspects of application behavior as well). Controller specs will continue to be supported until at least version 4.0 (see the [release notes](http://rspec.info/blog/2016/07/rspec-3-5-has-been-released/#rails-support-for-rails-5) for details). For more information, see [cucumber scenarios for controller specs](https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs). ## Feature Specs Feature specs test your application from the outside by simulating a browser. [`capybara`](https://github.com/jnicklas/capybara) is used to manage the simulated browser. Feature specs default to residing in the `spec/features` folder. Tagging any context with the metadata `:type => :feature` treats its examples as feature specs. Feature specs mix in functionality from the capybara gem, thus they require `capybara` to use. To use feature specs, add `capybara` to the `Gemfile`: ```ruby gem "capybara" ``` For more information, see the [cucumber scenarios for feature specs](https://www.relishapp.com/rspec/rspec-rails/v/3-4/docs/feature-specs/feature-spec). ## Mailer specs By default Mailer specs reside in the `spec/mailers` folder. Adding the metadata `:type => :mailer` to any context makes its examples be treated as mailer specs. `ActionMailer::TestCase::Behavior` is mixed into your mailer specs. ```ruby require "rails_helper" RSpec.describe Notifications, :type => :mailer do describe "notify" do let(:mail) { Notifications.signup } it "renders the headers" do expect(mail.subject).to eq("Signup") expect(mail.to).to eq(["to@example.org"]) expect(mail.from).to eq(["from@example.com"]) end it "renders the body" do expect(mail.body.encoded).to match("Hi") end end end ``` For more information, see the [cucumber scenarios for mailer specs ](https://relishapp.com/rspec/rspec-rails/v/3-4/docs/mailer-specs). ## Job specs Tagging a context with the metadata `:type => :job` treats its examples as job specs. Typically these specs will live in `spec/jobs`. ```ruby require 'rails_helper' RSpec.describe UploadBackupsJob, :type => :job do describe "#perform_later" do it "uploads a backup" do ActiveJob::Base.queue_adapter = :test UploadBackupsJob.perform_later('backup') expect(UploadBackupsJob).to have_been_enqueued end end end ``` For more information, see the [cucumber scenarios for job specs ](https://relishapp.com/rspec/rspec-rails/docs/job-specs). ## View specs View specs default to residing in the `spec/views` folder. Tagging any context with the metadata `:type => :view` treats its examples as view specs. View specs mix in `ActionView::TestCase::Behavior`. ```ruby require 'rails_helper' RSpec.describe "events/index", :type => :view do it "renders _event partial for each event" do assign(:events, [double(Event), double(Event)]) render expect(view).to render_template(:partial => "_event", :count => 2) end end RSpec.describe "events/show", :type => :view do it "displays the event location" do assign(:event, Event.new(: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, Widget.new) render ``` The code above assigns `Widget.new` 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 = Widget.new 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 default to residing in the `spec/routing` folder. Tagging any context with the metadata `:type => :routing` treats its examples as routing specs. ```ruby require 'rails_helper' RSpec.describe "routing to profiles", :type => :routing 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 default to residing in the `spec/helpers` folder. Tagging any context with the metadata `:type => :helper` treats its examples as helper specs. Helper specs mix in ActionView::TestCase::Behavior. A `helper` object is provided which mixes in the helper module being spec'd, along with `ApplicationHelper` (if present). ```ruby require 'rails_helper' RSpec.describe EventsHelper, :type => :helper 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 Several domain-specific matchers are provided to each of the example group types. Most simply delegate to their equivalent 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 standard CRUD routes which should not be routable. ```ruby expect(:get => "/widgets/1/edit").not_to be_routable ``` ### `have_http_status` - Passes if `response` has a matching HTTP status code - The following symbolic status codes are allowed: - `Rack::Utils::SYMBOL_TO_STATUS_CODE` - One of the defined `ActionDispatch::TestResponse` aliases: - `:error` - `:missing` - `:redirect` - `:success` - Available in controller, feature, and request specs. In controller and request specs, apply to the `response` object: ```ruby expect(response).to have_http_status(201) expect(response).not_to have_http_status(:created) ``` In feature specs, apply to the `page` object: ```ruby expect(page).to have_http_status(:success) ``` ## `rake` tasks Several rake tasks are provided as a convenience for working with RSpec. To run the entire spec suite use `rake spec`. To run a subset of specs use the associated type task, for example `rake spec:models`. A full list of the available rake tasks can be seen by running `rake -T | grep spec`. ### 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 ``` ## Also see * [https://github.com/rspec/rspec](https://github.com/rspec/rspec) * [https://github.com/rspec/rspec-core](https://github.com/rspec/rspec-core) * [https://github.com/rspec/rspec-expectations](https://github.com/rspec/rspec-expectations) * [https://github.com/rspec/rspec-mocks](https://github.com/rspec/rspec-mocks) ## Feature Requests & Bugs See rspec-rails-3.7.2/README_DEV.md000066400000000000000000000015511320451746500157350ustar00rootroot00000000000000# rspec-rails development This documentation is meant for folks contributing the rspec-rails project itself. ## Background rspec-rails lives in a complicated ecosystem. We run our specs against multiple Rails and Ruby versions. ### Default By default, rspec-rails' test suite will run against the latest stable version of Rails. ### Running Tests ```bash bundle install --binstubs bin/rake ``` ### Errors If you receive an error from `bundler` where constraints cannot be satisfied for Rails, try removing `Gemfile.lock` (`rm Gemfile.lock`) and running `bundle install --binstubs` again. This can happen if the `Gemfile.lock` was generated for a different version of Rails than you are trying to use now. ### Changing Rails Version To run the specs against a different version of Rails, use the `thor` command: ```bash bin/thor version:use 3.2.13 bin/rake ``` rspec-rails-3.7.2/Rakefile000066400000000000000000000144701320451746500154310ustar00rootroot00000000000000require "bundler" begin Bundler.setup Bundler::GemHelper.install_tasks rescue raise "You need to install a bundle first. Try 'thor version:use 3.2.13'" end require 'yaml' require 'rspec' require 'rspec/core/rake_task' require 'cucumber/rake/task' def rails_template_command require "rails" if Rails.version.to_f >= 5.0 "app:template" else "rails:template" end end 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) do |t| version = ENV.fetch("RAILS_VERSION", "~> 4.2.0")[/\d[\.-]\d/] tags = [] if version.to_f >= 5.1 tags << "~@rails_pre_5.1" end if version.to_f >= 5.0 tags << "~@rails_pre_5" end if version.to_f == 5.0 tags << "~@system_test" end if tags.empty? tags << "~@rails_post_5" tags << "~@system_test" end cucumber_flag = tags.map { |tag| "--tag #{tag}" } t.cucumber_opts = cucumber_flag end namespace :generate do desc "generate a fresh app with rspec installed" task :app do |_task| 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 --no-rc --skip-javascript --skip-sprockets --skip-git --skip-test-unit --skip-listen --skip-bundle --template=example_app_generator/generate_app.rb" in_example_app do sh "./travis_retry_bundle_install.sh 2>&1" # Rails 4 cannot use a `rails` binstub generated by Bundler sh "bundle binstubs bundler rspec-core rake --force" sh "bundle binstubs railties" unless File.exist?("bin/rails") 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 desc "generate a bunch of stuff with generators" task :stuff do in_example_app "bin/rake #{rails_template_command} LOCATION='../../example_app_generator/generate_stuff.rb'" end end def in_example_app(*command_opts) app_dir = './tmp/example_app' if Hash === command_opts.last opts = command_opts.pop app_dir = opts.fetch(:app_dir, app_dir) end Dir.chdir(app_dir) do Bundler.with_original_env do ENV["BUNDLE_GEMFILE"] = "Gemfile" sh *command_opts unless command_opts.empty? yield if block_given? 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='../../example_app_generator/run_specs.rb' bin/rake #{rails_template_command} --backtrace" end namespace :smoke do desc "create a new example app with generated specs and run them" task :app => ["clobber:app", "generate:app", "generate:stuff", :smoke] 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 namespace :no_active_record do example_app_dir = './tmp/no_ar_example_app' desc "run a variety of specs against a non-ActiveRecord generated app" task :smoke do in_example_app "LOCATION='../../example_app_generator/run_specs.rb' bin/rake #{rails_template_command} --backtrace", :app_dir => example_app_dir end namespace :smoke do desc "create a new example app without active record including generated specs and run them" task :app => [ "no_active_record:clobber", "no_active_record:generate:app", "no_active_record:generate:stuff", "no_active_record:smoke", ] end desc "remove the old non-ActiveRecord app" task :clobber do rm_rf example_app_dir end namespace :generate do desc "generate a fresh app with no active record" task :app do unless File.directory?(example_app_dir) 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 #{example_app_dir} --no-rc --skip-active-record --skip-javascript --skip-sprockets --skip-git --skip-test-unit --skip-listen --skip-bundle --template=example_app_generator/generate_app.rb" in_example_app(:app_dir => example_app_dir) do sh "./travis_retry_bundle_install.sh 2>&1" # Rails 4 cannot use a `rails` binstub generated by Bundler sh "bundle binstubs bundler rspec-core rake --force" sh "bundle binstubs railties" unless File.exist?("bin/rails") 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 desc "generate a bunch of stuff with generators" task :stuff do in_example_app "bin/rake #{rails_template_command} LOCATION='../../example_app_generator/generate_stuff.rb'", :app_dir => example_app_dir end end end task :acceptance => ['smoke:app', 'no_active_record:smoke:app', :cucumber] task :default => [:spec, :acceptance] task :verify_private_key_present do private_key = File.expand_path('~/.gem/rspec-gem-private_key.pem') unless File.exist?(private_key) raise "Your private key is not present. This gem should not be built without that." end end task :build => :verify_private_key_present rspec-rails-3.7.2/Thorfile000066400000000000000000000005461320451746500154620ustar00rootroot00000000000000class Version < Thor include Thor::Actions desc "use VERSION", "installs the bundle the rails-VERSION" def use(version) remove_file "Gemfile.lock" run "echo '#{version}' > ./.rails-version" run "bundle install --binstubs" end desc "which", "print out the configured rails version" def which say `cat ./.rails-version` end end rspec-rails-3.7.2/appveyor.yml000066400000000000000000000016251320451746500163520ustar00rootroot00000000000000# This file was generated on 2017-09-15T10:18:21+09:00 from the rspec-dev repo. # DO NOT modify it by hand as your changes will get lost the next time it is generated. version: "{build}" # This will build all PRs targetting matching branches. # Without this, each PR builds twice -- once for the PR branch HEAD, # and once for the merge commit that github creates for each mergable PR. branches: only: - master - /.*-maintenance$/ # Disable normal Windows builds in favor of our test script. build: off install: - SET PATH=C:\Ruby%ruby_version%\bin;%PATH% - ruby --version - gem --version - gem install bundler -v "!= 1.12.0, != 1.12.1, != 1.12.2, != 1.12.3" - bundler --version - bundle install - cinst ansicon test_script: - bundle exec rspec --backtrace environment: matrix: # ruby_version: '20' doesn't work for some reason - ruby_version: '193' - ruby_version: '21' rspec-rails-3.7.2/benchmarks/000077500000000000000000000000001320451746500160735ustar00rootroot00000000000000rspec-rails-3.7.2/benchmarks/before_block_capture_block_vs_yield.rb000066400000000000000000000150361320451746500256340ustar00rootroot00000000000000require 'benchmark/ips' def before_n_times(n, &block) n.times { instance_exec(&block) } end def yield_n_times(n) before_n_times(n) { yield } end def capture_block_and_yield_n_times(n, &block) before_n_times(n) { yield } end def capture_block_and_call_n_times(n, &block) before_n_times(n) { block.call } end [10, 25, 50, 100, 1000, 10000].each do |count| puts "\n\nInvoking the block #{count} times\n" Benchmark.ips do |x| x.report("Yield #{count} times ") do yield_n_times(count) { } end x.report("Capture block and yield #{count} times") do capture_block_and_yield_n_times(count) { } end x.report("Capture block and call #{count} times ") do capture_block_and_call_n_times(count) { } end end end __END__ This attemps to measure the performance of how `routes` works in RSpec. It's actually a method which delegates to `before`. RSpec executes `before` hooks by capturing the block and then performing an `instance_exec` on it later in the example context. rspec-core has already performed [many related benchmarks about this](https://github.com/rspec/rspec-core/tree/master/benchmarks): - [call vs yield](https://github.com/rspec/rspec-core/blob/master/benchmarks/call_v_yield.rb) - [capture block vs yield](https://github.com/rspec/rspec-core/blob/master/benchmarks/capture_block_vs_yield.rb) - [flat map vs inject](https://github.com/rspec/rspec-core/blob/master/benchmarks/flat_map_vs_inject.rb) The results are very interesting: > This benchmark demonstrates that capturing a block (e.g. `&block`) has > a high constant cost, taking about 5x longer than a single `yield` > (even if the block is never used!). > > However, fowarding a captured block can be faster than using `yield` > if the block is used many times (the breakeven point is at about 20-25 > invocations), so it appears that he per-invocation cost of `yield` > is higher than that of a captured-and-forwarded block. > > Note that there is no circumstance where using `block.call` is faster. > > See also `flat_map_vs_inject.rb`, which appears to contradict these > results a little bit. > > -- https://github.com/rspec/rspec-core/blob/master/benchmarks/capture_block_vs_yield.rb#L83-L95 and > Surprisingly, `flat_map(&block)` appears to be faster than > `flat_map { yield }` in spite of the fact that our array here > is smaller than the break-even point of 20-25 measured in the > `capture_block_vs_yield.rb` benchmark. In fact, the forwaded-block > version remains faster in my benchmarks here no matter how small > I shrink the `words` array. I'm not sure why! > > -- https://github.com/rspec/rspec-core/blob/master/benchmarks/flat_map_vs_inject.rb#L37-L42 This seems to show that the error margin is enough to negate any benefit from capturing the block initially. It also shows that not capturing the block is still faster at low rates of calling. If this holds for your system, I think this PR is good as is and we won't need to capture the block in the `route` method, but still use `yield`. My results using Ruby 2.2.0: Invoking the block 10 times Calculating ------------------------------------- Yield 10 times 13.127k i/100ms Capture block and yield 10 times 12.975k i/100ms Capture block and call 10 times 11.524k i/100ms ------------------------------------------------- Yield 10 times 165.030k (± 5.7%) i/s - 827.001k Capture block and yield 10 times 163.866k (± 5.9%) i/s - 817.425k Capture block and call 10 times 137.892k (± 7.3%) i/s - 691.440k Invoking the block 25 times Calculating ------------------------------------- Yield 25 times 7.305k i/100ms Capture block and yield 25 times 7.314k i/100ms Capture block and call 25 times 6.047k i/100ms ------------------------------------------------- Yield 25 times 84.167k (± 5.6%) i/s - 423.690k Capture block and yield 25 times 82.110k (± 6.4%) i/s - 409.584k Capture block and call 25 times 67.144k (± 6.2%) i/s - 338.632k Invoking the block 50 times Calculating ------------------------------------- Yield 50 times 4.211k i/100ms Capture block and yield 50 times 4.181k i/100ms Capture block and call 50 times 3.410k i/100ms ------------------------------------------------- Yield 50 times 45.223k (± 5.0%) i/s - 227.394k Capture block and yield 50 times 45.253k (± 4.9%) i/s - 225.774k Capture block and call 50 times 36.181k (± 5.7%) i/s - 180.730k Invoking the block 100 times Calculating ------------------------------------- Yield 100 times 2.356k i/100ms Capture block and yield 100 times 2.305k i/100ms Capture block and call 100 times 1.842k i/100ms ------------------------------------------------- Yield 100 times 23.677k (± 7.1%) i/s - 117.800k Capture block and yield 100 times 24.039k (± 4.7%) i/s - 122.165k Capture block and call 100 times 18.888k (± 6.6%) i/s - 95.784k Invoking the block 1000 times Calculating ------------------------------------- Yield 1000 times 244.000 i/100ms Capture block and yield 1000 times 245.000 i/100ms Capture block and call 1000 times 192.000 i/100ms ------------------------------------------------- Yield 1000 times 2.540k (± 4.3%) i/s - 12.688k Capture block and yield 1000 times 2.499k (± 5.6%) i/s - 12.495k Capture block and call 1000 times 1.975k (± 5.1%) i/s - 9.984k Invoking the block 10000 times Calculating ------------------------------------- Yield 10000 times 24.000 i/100ms Capture block and yield 10000 times 24.000 i/100ms Capture block and call 10000 times 19.000 i/100ms ------------------------------------------------- Yield 10000 times 232.923 (±15.5%) i/s - 1.128k Capture block and yield 10000 times 212.504 (±21.6%) i/s - 936.000 Capture block and call 10000 times 184.090 (±10.3%) i/s - 912.000 rspec-rails-3.7.2/cucumber.yml000066400000000000000000000002361320451746500163070ustar00rootroot00000000000000default: --require features --format progress --tags ~@wip pretty: --require features --format pretty --tags ~@wip wip: --require features --tags @wip rspec-rails-3.7.2/example_app_generator/000077500000000000000000000000001320451746500203175ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/app/000077500000000000000000000000001320451746500210775ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/app/views/000077500000000000000000000000001320451746500222345ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/app/views/foo.html000066400000000000000000000000411320451746500237000ustar00rootroot00000000000000Static template named 'foo.html' rspec-rails-3.7.2/example_app_generator/app/views/some_templates/000077500000000000000000000000001320451746500252555ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/app/views/some_templates/bar.html000066400000000000000000000000411320451746500267020ustar00rootroot00000000000000Static template named 'bar.html' rspec-rails-3.7.2/example_app_generator/generate_action_mailer_specs.rb000066400000000000000000000031631320451746500265240ustar00rootroot00000000000000require 'active_support' require 'active_support/core_ext/module' # We need to copy this method from Thor for older Rails versions def comment_lines(path, flag, *args) flag = flag.respond_to?(:source) ? flag.source : flag gsub_file(path, /^(\s*)([^#|\n]*#{flag})/, '\1# \2', *args) end using_source_path(File.expand_path('..', __FILE__)) do # Comment out the default mailer stuff comment_lines 'config/environments/development.rb', /action_mailer/ comment_lines 'config/environments/test.rb', /action_mailer/ initializer 'action_mailer.rb', <<-CODE require "action_view/base" if ENV['DEFAULT_URL'] if ::Rails::VERSION::STRING < '4.1' ExampleApp::Application.configure do config.action_mailer.default_url_options = { :host => ENV['DEFAULT_URL'] } end else Rails.application.configure do config.action_mailer.default_url_options = { :host => ENV['DEFAULT_URL'] } end end end if defined?(ActionMailer) && Rails::VERSION::MAJOR < 4 # This will force the loading of ActionMailer settings ActionMailer::Base.smtp_settings end CODE gsub_file 'config/initializers/action_mailer.rb', /ExampleApp/, Rails.application.class.parent.to_s copy_file 'spec/support/default_preview_path' chmod 'spec/support/default_preview_path', 0755 gsub_file 'spec/support/default_preview_path', /ExampleApp/, Rails.application.class.parent.to_s if skip_active_record? comment_lines 'spec/support/default_preview_path', /active_record/ end copy_file 'spec/verify_mailer_preview_path_spec.rb' end rspec-rails-3.7.2/example_app_generator/generate_app.rb000066400000000000000000000047721320451746500233100ustar00rootroot00000000000000require 'nokogiri/version' rspec_rails_repo_path = File.expand_path("../../", __FILE__) rspec_dependencies_gemfile = File.join(rspec_rails_repo_path, 'Gemfile-rspec-dependencies') rails_dependencies_gemfile = File.join(rspec_rails_repo_path, 'Gemfile-rails-dependencies') bundle_install_path = File.join(rspec_rails_repo_path, '..', 'bundle') maintenance_branch_file = File.join(rspec_rails_repo_path, 'maintenance-branch') travis_retry_script = File.join( rspec_rails_repo_path, 'example_app_generator', 'travis_retry_bundle_install.sh' ) function_script_file = File.join(rspec_rails_repo_path, 'script/functions.sh') in_root do prepend_to_file "Rakefile", "require 'active_support/all'" # Remove the existing rails version so we can properly use master or other # edge branches gsub_file 'Gemfile', /^.*\bgem 'rails.*$/, '' gsub_file "Gemfile", /.*web-console.*/, '' gsub_file "Gemfile", /.*debugger.*/, '' gsub_file "Gemfile", /.*byebug.*/, "gem 'byebug', '~> 9.0.6'" gsub_file "Gemfile", /.*puma.*/, "" if Rails::VERSION::STRING >= '5.0.0' append_to_file('Gemfile', "gem 'rails-controller-testing', :git => 'https://github.com/rails/rails-controller-testing'\n") end # Nokogiri version is pinned in rspec-rails' Gemfile since it tend to cause installation problems # on Travis CI, so we pin nokogiri in this example app also. append_to_file 'Gemfile', "gem 'nokogiri', '#{Nokogiri::VERSION}'\n" # Use our version of RSpec and Rails append_to_file 'Gemfile', <<-EOT.gsub(/^ +\|/, '') |# Rack::Cache 1.3.0 requires Ruby >= 2.0.0 |gem 'rack-cache', '< 1.3.0' if RUBY_VERSION < '2.0.0' | |if RUBY_VERSION >= '1.9.3' | gem 'rake', '>= 10.0.0' |else | gem 'rake', '~> 10.0' # rake 11 requires Ruby 1.9.3 or later |end | |# Version 3 of mime-types 3 requires Ruby 2.0 |if RUBY_VERSION < '2.0.0' | gem 'mime-types', '< 3' |end | |gem 'rspec-rails', | :path => '#{rspec_rails_repo_path}', | :groups => [:development, :test] |eval_gemfile '#{rspec_dependencies_gemfile}' |eval_gemfile '#{rails_dependencies_gemfile}' EOT copy_file maintenance_branch_file, 'maintenance-branch' copy_file travis_retry_script, 'travis_retry_bundle_install.sh' gsub_file 'travis_retry_bundle_install.sh', 'FUNCTIONS_SCRIPT_FILE', function_script_file gsub_file 'travis_retry_bundle_install.sh', 'REPLACE_BUNDLE_PATH', bundle_install_path chmod 'travis_retry_bundle_install.sh', 0755 end rspec-rails-3.7.2/example_app_generator/generate_stuff.rb000066400000000000000000000075261320451746500236570ustar00rootroot00000000000000require 'rspec/rails/feature_check' DEFAULT_SOURCE_PATH = File.expand_path('..', __FILE__) module ExampleAppHooks module AR def source_paths @__source_paths__ ||= [DEFAULT_SOURCE_PATH] end def setup_tasks # no-op end def final_tasks copy_file 'spec/verify_active_record_spec.rb' copy_file 'app/views/foo.html' copy_file 'app/views/some_templates/bar.html' copy_file 'spec/verify_custom_renderers_spec.rb' copy_file 'spec/verify_fixture_warning_spec.rb' run('bin/rake db:migrate') if ::Rails::VERSION::STRING.to_f < 4.1 run('bin/rake db:migrate RAILS_ENV=test') end end def skip_active_record? false end end module NoAR def source_paths @__source_paths__ ||= [File.join(DEFAULT_SOURCE_PATH, 'no_active_record')] end def setup_tasks copy_file 'app/models/in_memory/model.rb' copy_file 'lib/rails/generators/in_memory/model/model_generator.rb' copy_file 'lib/rails/generators/in_memory/model/templates/model.rb.erb' application <<-CONFIG config.generators do |g| g.orm :in_memory, :migration => false end CONFIG end def final_tasks copy_file 'spec/verify_no_active_record_spec.rb' end def skip_active_record? true end end def self.environment_hooks if defined?(ActiveRecord) AR else NoAR end end end def generate(*) super $?.success? || abort end def using_source_path(path) source_paths.unshift path yield ensure # Remove our path munging source_paths.shift end # Generally polluting `main` is bad as it monkey patches all objects. In this # context, `self` is an _instance_ of a `Rails::Generators::AppGenerator`. So # this won't pollute anything. extend ExampleAppHooks.environment_hooks setup_tasks generate('rspec:install') generate('controller wombats index') # plural generate('controller welcome index') # singular generate('rspec:request wombats') 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') if ::Rails::VERSION::STRING.to_f < 4.0 generate('scaffold gadget') # scaffold with no attributes generate('scaffold ticket original_price:float discounted_price:float') generate('scaffold admin/account name:string') # scaffold with nested resource generate('rspec:feature gadget') generate('controller things custom_action') using_source_path(File.expand_path('..', __FILE__)) do # rspec-core loads files alphabetically, so we want this to be the first one copy_file 'spec/features/model_mocks_integration_spec.rb' end begin require 'active_job' generate('job upload_backups') rescue LoadError end file "app/views/things/custom_action.html.erb", "This is a template for a custom action.", :force => true file "app/views/errors/401.html.erb", "This is a template for rendering an error page", :force => true # Use the absolute path so we can load it without active record too apply File.join(DEFAULT_SOURCE_PATH, 'generate_action_mailer_specs.rb') using_source_path(File.expand_path('..', __FILE__)) do # rspec-core loads files alphabetically, so we want this to be the first one copy_file 'spec/__verify_fixture_load_order_spec.rb' end gsub_file 'spec/spec_helper.rb', /^=(begin|end)/, '' # Warnings are too noisy in the sample apps gsub_file 'spec/spec_helper.rb', 'config.warnings = true', 'config.warnings = false' gsub_file '.rspec', '--warnings', '' # Remove skips so we can test controller specs work gsub_file 'spec/controllers/gadgets_controller_spec.rb', 'skip("Add a hash of attributes valid for your model")', '{}' final_tasks rspec-rails-3.7.2/example_app_generator/no_active_record/000077500000000000000000000000001320451746500236245ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/no_active_record/app/000077500000000000000000000000001320451746500244045ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/no_active_record/app/models/000077500000000000000000000000001320451746500256675ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/no_active_record/app/models/in_memory/000077500000000000000000000000001320451746500276655ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/no_active_record/app/models/in_memory/model.rb000066400000000000000000000033611320451746500313150ustar00rootroot00000000000000# Rails 4.0.x seems to be the only version that does not autoload `ActiveModel` require 'active_model' raise "ActiveRecord is defined but should not be!" if defined?(::ActiveRecord) module InMemory module Persistence def all @all_records ||= [] end def count all.length end alias_method :size, :count alias_method :length, :count def last all.last end def find(id) id = id.to_i all.find { |record| record.id == id } || raise end def create!(attributes = {}) record = new(attributes) record.save record end def next_id @id_count ||= 0 @id_count += 1 end end class Model extend Persistence if defined?(::ActiveModel::Model) include ::ActiveModel::Model else extend ::ActiveModel::Naming include ::ActiveModel::Conversion include ::ActiveModel::Validations def initialize(attributes = {}) assign_attributes(attributes) end end attr_accessor :id, :persisted alias_method :persisted?, :persisted def update(attributes) assign_attributes(attributes) save end alias_method :update_attributes, :update def assign_attributes(attributes) attributes.each do |name, value| __send__("#{name}=", value) end end def save(*) self.id = self.class.next_id self.class.all << self true end def destroy self.class.all.delete(self) true end def reload(*) self end def ==(other) other.is_a?(self.class) && id == other.id end def persisted? !id.nil? end def new_record? !persisted? end def to_param id.to_s end end end rspec-rails-3.7.2/example_app_generator/no_active_record/lib/000077500000000000000000000000001320451746500243725ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/no_active_record/lib/rails/000077500000000000000000000000001320451746500255045ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/no_active_record/lib/rails/generators/000077500000000000000000000000001320451746500276555ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/no_active_record/lib/rails/generators/in_memory/000077500000000000000000000000001320451746500316535ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/no_active_record/lib/rails/generators/in_memory/model/000077500000000000000000000000001320451746500327535ustar00rootroot00000000000000model_generator.rb000066400000000000000000000014271320451746500363730ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/no_active_record/lib/rails/generators/in_memory/model# Hook into the work already done to support older Rails require 'generators/rspec' module InMemory module Generators class ModelGenerator < ::Rspec::Generators::Base source_root File.expand_path('../templates', __FILE__) desc "Creates a Fake ActiveRecord acting model" argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" check_class_collision class_option :parent, :type => :string, :desc => "The parent class for the generated model" def create_model_file template "model.rb.erb", File.join("app/models", class_path, "#{file_name}.rb") end hook_for :test_framework end end end templates/000077500000000000000000000000001320451746500346725ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/no_active_record/lib/rails/generators/in_memory/modelmodel.rb.erb000066400000000000000000000003321320451746500370640ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/no_active_record/lib/rails/generators/in_memory/model/templates<% module_namespacing do -%> class <%= class_name %> < <%= options[:parent].try(:classify) || 'InMemory::Model' %> <% attributes.each do |attribute| -%> attr_accessor :<%= attribute.name %> <% end -%> end <% end -%> rspec-rails-3.7.2/example_app_generator/no_active_record/spec/000077500000000000000000000000001320451746500245565ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/no_active_record/spec/verify_no_active_record_spec.rb000066400000000000000000000002341320451746500330050ustar00rootroot00000000000000require 'rails_helper' RSpec.describe 'Example App' do it "does not have ActiveRecord defined" do expect(defined?(ActiveRecord)).not_to be end end rspec-rails-3.7.2/example_app_generator/run_specs.rb000066400000000000000000000011141320451746500226420ustar00rootroot00000000000000run('bin/rspec spec -cfdoc') || abort # Ensure we test the issue in-case this isn't the first spec file loaded run( 'bin/rspec --backtrace -cfdoc spec/__verify_fixture_load_order_spec.rb' ) || abort run('bin/rake --backtrace spec') || abort run('bin/rake --backtrace spec:requests') || abort run('bin/rake --backtrace spec:models') || abort run('bin/rake --backtrace spec:views') || abort run('bin/rake --backtrace spec:controllers') || abort run('bin/rake --backtrace spec:helpers') || abort run('bin/rake --backtrace spec:mailers') || abort run("bin/rake --backtrace stats") || abort rspec-rails-3.7.2/example_app_generator/spec/000077500000000000000000000000001320451746500212515ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/spec/__verify_fixture_load_order_spec.rb000066400000000000000000000003171320451746500303530ustar00rootroot00000000000000# This spec needs to be run before `rails_helper` is loaded to check the issue RSpec.describe "Verify issue rspec/rspec-rails#1355" do it "passes" do expect(1).to eq 1 end end require 'rails_helper' rspec-rails-3.7.2/example_app_generator/spec/features/000077500000000000000000000000001320451746500230675ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/spec/features/model_mocks_integration_spec.rb000066400000000000000000000006521320451746500313300ustar00rootroot00000000000000require 'rails_helper' RSpec.describe "Using rspec-mocks with models" do it "supports stubbing class methods on models" do allow(Widget).to receive(:all).and_return(:any_stub) expect(Widget.all).to be :any_stub end it "supports stubbing attribute methods on models" do a_widget = Widget.new allow(a_widget).to receive(:name).and_return("Any Stub") expect(a_widget.name).to eq "Any Stub" end end rspec-rails-3.7.2/example_app_generator/spec/support/000077500000000000000000000000001320451746500227655ustar00rootroot00000000000000rspec-rails-3.7.2/example_app_generator/spec/support/default_preview_path000077500000000000000000000040461320451746500271200ustar00rootroot00000000000000#!/usr/bin/env ruby # Transparent helper to simply document code sections def require_file_stub(name) yield end ENV['RAILS_ENV'] ||= 'development' require_file_stub 'config/environment' do # Load the Rails application. require_file_stub 'config/application' do require_file_stub 'config/boot' do # Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) end # Pick the frameworks you want: require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" unless ENV['NO_ACTION_MAILER'] require "action_view/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. if Rails::VERSION::STRING.to_f < 3.1 Bundler.require(:default, Rails.env) else Bundler.require(*Rails.groups) end module ExampleApp class Application < Rails::Application config.eager_load = false config.eager_load_paths.clear if Rails::VERSION::MAJOR < 4 # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false unless ENV['NO_ACTION_MAILER'] if ENV['CUSTOM_PREVIEW_PATH'] config.action_mailer.preview_path = ENV['CUSTOM_PREVIEW_PATH'] end if ENV['SHOW_PREVIEWS'] config.action_mailer.show_previews = (ENV['SHOW_PREVIEWS'] == 'true') end end end I18n.enforce_available_locales = true if I18n.respond_to?(:enforce_available_locales) end # Initialize the Rails application. Rails.application.initialize! end exit if ENV['NO_ACTION_MAILER'] if ENV['DEFAULT_URL'] puts ActionMailer::Base.default_url_options[:host] elsif defined?(::ActionMailer::Preview) puts Rails.application.config.action_mailer.preview_path end # This will force the loading of ActionMailer settings to ensure we do not # accicentally set something we should not ActionMailer::Base.smtp_settings rspec-rails-3.7.2/example_app_generator/spec/verify_active_record_spec.rb000066400000000000000000000002161320451746500270040ustar00rootroot00000000000000require 'rails_helper' RSpec.describe 'Example App' do it "has ActiveRecord defined" do expect(defined?(ActiveRecord)).to be end end rspec-rails-3.7.2/example_app_generator/spec/verify_custom_renderers_spec.rb000066400000000000000000000067701320451746500275710ustar00rootroot00000000000000require 'rails_helper' RSpec.describe "template rendering", :type => :controller do context "without render_views" do context "with the standard renderers" do controller do def index render :template => 'foo', :layout => false end end it "renders the 'foo' template" do get :index expect(response).to render_template(:foo) end it "renders an empty string" do get :index expect(response.body).to eq("") end end context "with a String path prepended to the view path" do controller do def index prepend_view_path('app/views/some_templates') render :template => 'bar', :layout => false end end it "renders the 'bar' template" do get :index expect(response).to render_template(:bar) end it "renders an empty string" do get :index expect(response.body).to eq("") end end context "with a custom renderer prepended to the view path" do controller do def index prepend_view_path(MyResolver.new) render :template => 'baz', :layout => false end end it "renders the 'baz' template" do get :index expect(response).to render_template(:baz) end it "renders an empty string" do get :index expect(response.body).to eq("") end end end context "with render_views enabled" do render_views context "with the standard renderers" do controller do def index render :template => 'foo', :layout => false end end it "renders the 'foo' template" do get :index expect(response).to render_template(:foo) end it "renders the contents of the template" do get :index expect(response.body).to include("Static template named 'foo.html'") end end context "with a String path prepended to the view path" do controller do def index prepend_view_path('app/views/some_templates') render :template => 'bar', :layout => false end end it "renders the 'bar' template" do get :index expect(response).to render_template(:bar) end it "renders the contents of the template" do get :index expect(response.body).to include("Static template named 'bar.html'") end end context "with a custom renderer prepended to the view path" do controller do def index prepend_view_path(MyResolver.new) render :template => 'baz', :layout => false end end it "renders the 'baz' template" do get :index expect(response).to render_template(:baz) end it "renders the contents of the template" do get :index expect(response.body).to eq("Dynamic template with path '/baz'") end end end class MyResolver < ActionView::Resolver private def find_templates(name, prefix = nil, partial = false, details = {}, key = nil, locals = []) name.prepend("_") if partial path = [prefix, name].join("/") template = find_template(name, path) [template] end def find_template(name, path) ActionView::Template.new( "", name, lambda { |_template| %("Dynamic template with path '#{_template.virtual_path}'") }, :virtual_path => path, :format => :html ) end end end rspec-rails-3.7.2/example_app_generator/spec/verify_fixture_warning_spec.rb000066400000000000000000000027441320451746500274160ustar00rootroot00000000000000require 'rails_helper' RSpec.describe "Fixture warnings" do def generate_fixture_example_group(hook_type) RSpec.describe do include RSpec::Rails::RailsExampleGroup fixtures :things before(hook_type) do things :a end it "" do end end end it "Warns when a fixture call is made in a before :context call" do expect(RSpec).to receive(:warn_with).with(match(/Calling fixture method in before :context/)) generate_fixture_example_group(:context).run end it "Does not warn when a fixture call is made in a before :each call" do expect(RSpec).not_to receive(:warn_with) generate_fixture_example_group(:each).run end end RSpec.describe "Global fixture warnings" do def generate_fixture_example_group(hook_type) RSpec.describe do include RSpec::Rails::RailsExampleGroup before(hook_type) do things :a end it "" do end end end around do |ex| RSpec.configuration.global_fixtures = [:things] ex.call RSpec.configuration.global_fixtures = [] end it "warns when a global fixture call is made in a before :context call" do expect(RSpec).to receive(:warn_with).with(match(/Calling fixture method in before :context/)) generate_fixture_example_group(:context).run end it "does not warn when a global fixture call is made in a before :each call" do expect(RSpec).not_to receive(:warn_with) generate_fixture_example_group(:each).run end end rspec-rails-3.7.2/example_app_generator/spec/verify_mailer_preview_path_spec.rb000066400000000000000000000150621320451746500302260ustar00rootroot00000000000000require 'rails_helper' require 'rspec/rails/feature_check' RSpec.describe 'Action Mailer railtie hook' do CaptureExec = Struct.new(:io, :exit_status) do def ==(str) io == str end end def as_commandline(ops) cmd, ops = ops.reverse ops ||= {} cmd_parts = ops.map { |k, v| "#{k}=#{v}" } << cmd << '2>&1' cmd_parts.join(' ') end def capture_exec(*ops) io = if RUBY_VERSION.to_f < 1.9 IO.popen(as_commandline(ops)) else ops << { :err => [:child, :out] } IO.popen(ops) end # Necessary to ignore warnings from Rails code base out = io.readlines. reject { |line| line =~ /warning: circular argument reference/ }. join. chomp CaptureExec.new(out, $?.exitstatus) end def have_no_preview have_attributes(:io => be_blank, :exit_status => 0) end let(:exec_script) { File.expand_path(File.join(__FILE__, '../support/default_preview_path')) } if RSpec::Rails::FeatureCheck.has_action_mailer_show_preview? context 'in the development environment' do let(:custom_env) { { 'RAILS_ENV' => rails_env } } let(:rails_env) { 'development' } it 'sets the preview path to the default rspec path' do expect(capture_exec(custom_env, exec_script)).to eq( "#{::Rails.root}/spec/mailers/previews" ) end it 'respects the setting from `show_previews`' do expect( capture_exec( custom_env.merge('SHOW_PREVIEWS' => 'false'), exec_script ) ).to have_no_preview end it 'respects a custom `preview_path`' do expect( capture_exec( custom_env.merge('CUSTOM_PREVIEW_PATH' => '/custom/path'), exec_script ) ).to eq('/custom/path') end it 'allows initializers to set options' do expect( capture_exec( custom_env.merge('DEFAULT_URL' => 'test-host'), exec_script ) ).to eq('test-host') end it 'handles action mailer not being available' do expect( capture_exec( custom_env.merge('NO_ACTION_MAILER' => 'true'), exec_script ) ).to have_no_preview end end context 'in a non-development environment' do let(:custom_env) { { 'RAILS_ENV' => rails_env } } let(:rails_env) { 'test' } it 'does not set the preview path by default' do expect(capture_exec(custom_env, exec_script)).to have_no_preview end it 'respects the setting from `show_previews`' do expect( capture_exec(custom_env.merge('SHOW_PREVIEWS' => 'true'), exec_script) ).to eq("#{::Rails.root}/spec/mailers/previews") end it 'allows initializers to set options' do expect( capture_exec( custom_env.merge('DEFAULT_URL' => 'test-host'), exec_script ) ).to eq('test-host') end it 'handles action mailer not being available' do expect( capture_exec( custom_env.merge('NO_ACTION_MAILER' => 'true'), exec_script ) ).to have_no_preview end end elsif RSpec::Rails::FeatureCheck.has_action_mailer_preview? context 'in the development environment', 'without `show_previews`' do let(:custom_env) { { 'RAILS_ENV' => rails_env } } let(:rails_env) { 'development' } it 'sets the preview path to the default rspec path' do expect(capture_exec(custom_env, exec_script)).to eq( "#{::Rails.root}/spec/mailers/previews" ) end it 'respects a custom `preview_path`' do expect( capture_exec( custom_env.merge('CUSTOM_PREVIEW_PATH' => '/custom/path'), exec_script ) ).to eq('/custom/path') end it 'allows initializers to set options' do expect( capture_exec( custom_env.merge('DEFAULT_URL' => 'test-host'), exec_script ) ).to eq('test-host') end it 'handles action mailer not being available' do expect( capture_exec( custom_env.merge('NO_ACTION_MAILER' => 'true'), exec_script ) ).to have_no_preview end end context 'in a non-development environment', 'without `show_previews`' do let(:custom_env) { { 'RAILS_ENV' => rails_env } } let(:rails_env) { 'test' } it 'does not set the preview path by default' do expect(capture_exec(custom_env, exec_script)).to have_no_preview end it 'respects a custom `preview_path`' do expect( capture_exec( custom_env.merge('CUSTOM_PREVIEW_PATH' => '/custom/path'), exec_script ) ).to eq('/custom/path') end it 'handles action mailer not being available' do expect( capture_exec( custom_env.merge('NO_ACTION_MAILER' => 'true'), exec_script ) ).to have_no_preview end end else context 'in the development environment' do let(:custom_env) { { 'RAILS_ENV' => rails_env } } let(:rails_env) { 'development' } it 'handles no action mailer preview' do expect(capture_exec(custom_env, exec_script)).to have_no_preview end it 'allows initializers to set options' do expect( capture_exec( custom_env.merge('DEFAULT_URL' => 'test-host'), exec_script ) ).to eq('test-host') end it 'handles action mailer not being available' do expect( capture_exec( custom_env.merge('NO_ACTION_MAILER' => 'true'), exec_script ) ).to have_no_preview end end context 'in a non-development environment' do let(:custom_env) { { 'RAILS_ENV' => rails_env } } let(:rails_env) { 'test' } it 'handles no action mailer preview' do expect(capture_exec(custom_env, exec_script)).to have_no_preview end it 'allows initializers to set options' do expect( capture_exec( custom_env.merge('DEFAULT_URL' => 'test-host'), exec_script ) ).to eq('test-host') end it 'handles action mailer not being available' do expect( capture_exec( custom_env.merge('NO_ACTION_MAILER' => 'true'), exec_script ) ).to have_no_preview end end end end rspec-rails-3.7.2/example_app_generator/travis_retry_bundle_install.sh000077500000000000000000000005761320451746500265020ustar00rootroot00000000000000#!/bin/bash set -e source FUNCTIONS_SCRIPT_FILE echo "Starting bundle install using shared bundle path" if is_mri_192_plus; then travis_retry eval "RUBYOPT=$RUBYOPT:'--enable rubygems' bundle install --gemfile ./Gemfile --path REPLACE_BUNDLE_PATH --retry=3 --jobs=3" else travis_retry eval "bundle install --gemfile ./Gemfile --path REPLACE_BUNDLE_PATH --retry=3 --jobs=3" fi rspec-rails-3.7.2/features/000077500000000000000000000000001320451746500155745ustar00rootroot00000000000000rspec-rails-3.7.2/features/.nav000066400000000000000000000020751320451746500163650ustar00rootroot00000000000000- upgrade: - from_1x_to_2x.md (From rspec-rails-1.x to rspec-rails-2) - GettingStarted.md (Start from scratch) - Generators.md (Generators) - Transactions.md - Changelog.md - RailsVersions.md (Rails versions) - directory_structure.feature - backtrace_filtering.feature - model_specs: - transactional_examples.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-3.7.2/features/Generators.md000066400000000000000000000012501320451746500202250ustar00rootroot00000000000000RSpec spec are normally generated alongside other application components. For instance, `rails generate model` will also generate an RSpec spec file for the model. 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. RSpec generators can also be run independently. For instance, rails generate rspec:model widget will create a new spec file in `spec/models/widget_spec.rb`. The same generator pattern is available for all specs: * scaffold * model * controller * helper * view * mailer * observer * integration * feature * job rspec-rails-3.7.2/features/GettingStarted.md000066400000000000000000000044301320451746500210470ustar00rootroot00000000000000Install 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 Widget 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-3.7.2/features/README.md000066400000000000000000000025661320451746500170640ustar00rootroot00000000000000rspec-rails extends Rails' built-in testing framework to support rspec examples for requests, controllers, models, views, helpers, mailers and routing. ## Rails rspec-rails 3 supports Rails 3.x and 4.x. For earlier versions of Rails, you need [rspec-rails 1](https://github.com/dchelimsky/rspec-rails). For Rails 5.x, make sure you are using rspec-rails 3.5.0 or newer. ## 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', '~> 3.0.0' 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. ## 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-3.7.2/features/RailsVersions.md000066400000000000000000000004331320451746500207210ustar00rootroot00000000000000 rails version | rspec-rails version 2.3 | 1.3.4 3.0 | >= 2.0 3.1 | >= 2.6 3.2 | >= 2.9 4.0 | >= 2.14 4.1 | >= 3.0 4.2 | >= 3.1 5.0 | >= 3.5 5.1 | >= 3.6 rspec-rails-3.7.2/features/Transactions.md000066400000000000000000000053431320451746500205730ustar00rootroot00000000000000When you run `rails generate rspec:install`, the `spec/rails_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-3.7.2/features/backtrace_filtering.feature000066400000000000000000000023411320451746500231330ustar00rootroot00000000000000Feature: backtrace filtering The following configuration setting will filter out lines in backtraces that come from Rails gems in order to reduce the noise in test failure output: ```ruby RSpec.configure do |config| config.filter_rails_from_backtrace! end ``` `rspec` will always show the full backtrace output when run with the `--backtrace` commandline option. Background: Using `filter_rails_from_backtrace!` Given a file named "spec/failing_spec.rb" with: """ruby require "rails_helper" RSpec.configure do |config| config.filter_rails_from_backtrace! end RSpec.describe "Controller", :type => :controller do controller do def index raise "Something went wrong." end end describe "GET index" do it "raises an error" do get :index end end end """ Scenario: Using the bare `rspec` command When I run `rspec` Then the output should contain "1 example, 1 failure" And the output should not contain "activesupport" Scenario: Using `rspec --backtrace` When I run `rspec --backtrace` Then the output should contain "1 example, 1 failure" And the output should contain "activesupport" rspec-rails-3.7.2/features/controller_specs/000077500000000000000000000000001320451746500211545ustar00rootroot00000000000000rspec-rails-3.7.2/features/controller_specs/Cookies.md000066400000000000000000000035171320451746500231000ustar00rootroot00000000000000Controller 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-3.7.2/features/controller_specs/README.md000066400000000000000000000036311320451746500224360ustar00rootroot00000000000000Controller specs are marked by `:type => :controller` or if you have set `config.infer_spec_type_from_file_location!` by placing them in `spec/controllers`. 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: - [`render_template`](matchers/render-template-matcher) ```ruby expect(response).to render_template(:new) # wraps assert_template ``` - [`redirect_to`](matchers/redirect-to-matcher) ```ruby expect(response).to redirect_to(location) # wraps assert_redirected_to ``` - [`have_http_status`](matchers/have-http-status-matcher) ```ruby expect(response).to have_http_status(:created) ``` - [`be_a_new`](#) ```ruby expect(assigns(:widget)).to be_a_new(Widget) ``` ## Examples RSpec.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-3.7.2/features/controller_specs/anonymous_controller.feature000066400000000000000000000665721320451746500270440ustar00rootroot00000000000000Feature: anonymous controller Use the `controller` method to define an anonymous controller that will inherit from the described class. 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: ```ruby controller(BaseController) ``` You can also disable base type inference, in which case anonymous controllers will inherit from `ApplicationController` instead of the described class by default: ```ruby RSpec.configure do |c| c.infer_base_class_for_anonymous_controllers = false end RSpec.describe BaseController, :type => :controller do controller do def index; end ​# this normally creates an anonymous `BaseController` subclass, ​# however since `infer_base_class_for_anonymous_controllers` is ​# disabled, it creates a subclass of `ApplicationController` end end ``` Scenario: Specify error handling in `ApplicationController` with redirect Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "rails_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 RSpec.describe ApplicationController, :type => :controller 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 `ApplicationController` with render Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "rails_helper" class ApplicationController < ActionController::Base class AccessDenied < StandardError; end rescue_from AccessDenied, :with => :access_denied private def access_denied render "errors/401" end end RSpec.describe ApplicationController, :type => :controller do controller do def index raise ApplicationController::AccessDenied end end describe "handling AccessDenied exceptions" do it "renders the errors/401 template" do get :index expect(response).to render_template("errors/401") end end end """ When I run `rspec spec` Then the examples should all pass Scenario: Specify error handling in `ApplicationController` with render :file Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "rails_helper" class ApplicationController < ActionController::Base class AccessDenied < StandardError; end rescue_from AccessDenied, :with => :access_denied private def access_denied render :file => "errors/401" end end RSpec.describe ApplicationController, :type => :controller do controller do def index raise ApplicationController::AccessDenied end end describe "handling AccessDenied exceptions" do it "renders the errors/401 template" do get :index expect(response).to render_template("errors/401") end end end """ When I run `rspec spec` Then the examples should all pass Scenario: Specify error handling in a subclass Given a file named "spec/controllers/application_controller_subclass_spec.rb" with: """ruby require "rails_helper" class ApplicationController < ActionController::Base class AccessDenied < StandardError; end end class FoosController < ApplicationController rescue_from ApplicationController::AccessDenied, :with => :access_denied private def access_denied redirect_to "/401.html" end end RSpec.describe FoosController, :type => :controller do controller(FoosController) 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 @rails_pre_5 Scenario: Infer base class from the described class Given a file named "spec/controllers/base_class_can_be_inferred_spec.rb" with: """ruby require "rails_helper" class ApplicationController < ActionController::Base; end class FoosController < ApplicationController; end RSpec.describe FoosController, :type => :controller do controller do def index render :text => "Hello World" end end it "creates anonymous controller derived from FoosController" do expect(controller).to be_a_kind_of(FoosController) end end """ When I run `rspec spec` Then the examples should all pass @rails_post_5 Scenario: Infer base class from the described class Given a file named "spec/controllers/base_class_can_be_inferred_spec.rb" with: """ruby require "rails_helper" class ApplicationController < ActionController::Base; end class FoosController < ApplicationController; end RSpec.describe FoosController, :type => :controller do controller do def index render :plain => "Hello World" end end it "creates anonymous controller derived from FoosController" do expect(controller).to be_a_kind_of(FoosController) end end """ When I run `rspec spec` Then the examples should all pass @rails_pre_5 Scenario: Use `name` and `controller_name` from the described class Given a file named "spec/controllers/get_name_and_controller_name_from_described_class_spec.rb" with: """ruby require "rails_helper" class ApplicationController < ActionController::Base; end class FoosController < ApplicationController; end RSpec.describe "Access controller names", :type => :controller do controller FoosController do def index @name = self.class.name @controller_name = controller_name render :text => "Hello World" end end before do get :index end it "gets the class name as described" do expect(assigns[:name]).to eq('FoosController') end it "gets the controller_name as described" do expect(assigns[:controller_name]).to eq('foos') end end """ When I run `rspec spec` Then the examples should all pass @rails_post_5 Scenario: Use `name` and `controller_name` from the described class Given a file named "spec/controllers/get_name_and_controller_name_from_described_class_spec.rb" with: """ruby require "rails_helper" class ApplicationController < ActionController::Base; end class FoosController < ApplicationController; end RSpec.describe "Access controller names", :type => :controller do controller FoosController do def index @name = self.class.name @controller_name = controller_name render :plain => "Hello World" end end before do get :index end it "gets the class name as described" do expect(assigns[:name]).to eq('FoosController') end it "gets the controller_name as described" do expect(assigns[:controller_name]).to eq('foos') end end """ When I run `rspec spec` Then the examples should all pass @rails_pre_5 Scenario: Invoke `around_filter` and `around_action` in base class Given a file named "spec/controllers/application_controller_around_filter_spec.rb" with: """ruby require "rails_helper" class ApplicationController < ActionController::Base around_filter :an_around_filter def an_around_filter @callback_invoked = true yield end end RSpec.describe ApplicationController, :type => :controller do controller do def index render :nothing => true end end it "invokes the callback" do get :index expect(assigns[:callback_invoked]).to be_truthy end end """ When I run `rspec spec` Then the examples should all pass @rails_post_5 Scenario: Invoke `around_filter` and `around_action` in base class Given a file named "spec/controllers/application_controller_around_filter_spec.rb" with: """ruby require "rails_helper" class ApplicationController < ActionController::Base around_action :an_around_filter def an_around_filter @callback_invoked = true yield end end RSpec.describe ApplicationController, :type => :controller do controller do def index render :plain => "" end end it "invokes the callback" do get :index expect(assigns[:callback_invoked]).to be_truthy end end """ When I run `rspec spec` Then the examples should all pass @rails_pre_5 Scenario: Anonymous controllers only create resource routes Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "rails_helper" if defined?(ActionController::UrlGenerationError) ExpectedRoutingError = ActionController::UrlGenerationError else ExpectedRoutingError = ActionController::RoutingError end RSpec.describe ApplicationController, :type => :controller 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(ExpectedRoutingError) 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(ExpectedRoutingError) 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(ExpectedRoutingError) 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(ExpectedRoutingError) 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(ExpectedRoutingError) end end end """ When I run `rspec spec` Then the examples should all pass @rails_post_5 Scenario: Anonymous controllers only create resource routes Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "rails_helper" if defined?(ActionController::UrlGenerationError) ExpectedRoutingError = ActionController::UrlGenerationError else ExpectedRoutingError = ActionController::RoutingError end RSpec.describe ApplicationController, :type => :controller do controller do def index render :plain => "index called" end def create render :plain => "create called" end def new render :plain => "new called" end def show render :plain => "show called" end def edit render :plain => "edit called" end def update render :plain => "update called" end def destroy render :plain => "destroy called" end def willerror render :plain => "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, :params => { :id => "anyid" } expect(response.body).to eq "edit called" end it "requires the :id parameter" do expect { get :edit }.to raise_error(ExpectedRoutingError) end # And the rest... %w{get post put delete}.each do |calltype| it "responds to #{calltype}" do send(calltype, :edit, :params => {:id => "anyid"}) expect(response.body).to eq "edit called" end end end describe "#show" do it "responds to GET" do get :show, :params => { :id => "anyid" } expect(response.body).to eq "show called" end it "requires the :id parameter" do expect { get :show }.to raise_error(ExpectedRoutingError) end # And the rest... %w{get post put delete}.each do |calltype| it "responds to #{calltype}" do send(calltype, :show, :params => {:id => "anyid"}) expect(response.body).to eq "show called" end end end describe "#update" do it "responds to PUT" do put :update, :params => { :id => "anyid" } expect(response.body).to eq "update called" end it "requires the :id parameter" do expect { put :update }.to raise_error(ExpectedRoutingError) end # And the rest... %w{get post put delete}.each do |calltype| it "responds to #{calltype}" do send(calltype, :update, :params => {:id => "anyid"}) expect(response.body).to eq "update called" end end end describe "#destroy" do it "responds to DELETE" do delete :destroy, :params => { :id => "anyid" } expect(response.body).to eq "destroy called" end it "requires the :id parameter" do expect { delete :destroy }.to raise_error(ExpectedRoutingError) end # And the rest... %w{get post put delete}.each do |calltype| it "responds to #{calltype}" do send(calltype, :destroy, :params => {: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(ExpectedRoutingError) end end end """ When I run `rspec spec` Then the examples should all pass @rails_pre_5 Scenario: Draw custom routes for anonymous controllers Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "rails_helper" RSpec.describe ApplicationController, :type => :controller do controller do def custom render :text => "custom called" end end specify "manually draw the route to request a custom action" 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 @rails_post_5 Scenario: Draw custom routes for anonymous controllers Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "rails_helper" RSpec.describe ApplicationController, :type => :controller do controller do def custom render :plain => "custom called" end end specify "manually draw the route to request a custom action" 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 @rails_pre_5 Scenario: Draw custom routes for anonymous controllers which don't inherit from application controller Given a file named "spec/controllers/other_controller_spec.rb" with: """ruby require "rails_helper" class OtherController < ActionController::Base end RSpec.describe OtherController, :type => :controller do controller do def custom render :text => "custom called" end end specify "manually draw the route to request a custom action" do routes.draw { get "custom" => "other#custom" } get :custom expect(response.body).to eq "custom called" end end """ When I run `rspec spec` Then the examples should all pass @rails_post_5 Scenario: Draw custom routes for anonymous controllers which don't inherit from application controller Given a file named "spec/controllers/other_controller_spec.rb" with: """ruby require "rails_helper" class OtherController < ActionController::Base end RSpec.describe OtherController, :type => :controller do controller do def custom render :plain => "custom called" end end specify "manually draw the route to request a custom action" do routes.draw { get "custom" => "other#custom" } get :custom expect(response.body).to eq "custom called" end end """ When I run `rspec spec` Then the examples should all pass @rails_pre_5 Scenario: Draw custom routes for defined controllers Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "rails_helper" class FoosController < ApplicationController; end RSpec.describe ApplicationController, :type => :controller do controller FoosController do def custom render :text => "custom called" end end specify "manually draw the route to request a custom action" do routes.draw { get "custom" => "foos#custom" } get :custom expect(response.body).to eq "custom called" end end """ When I run `rspec spec` Then the examples should all pass @rails_post_5 Scenario: Draw custom routes for defined controllers Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "rails_helper" class FoosController < ApplicationController; end RSpec.describe ApplicationController, :type => :controller do controller FoosController do def custom render :plain => "custom called" end end specify "manually draw the route to request a custom action" do routes.draw { get "custom" => "foos#custom" } get :custom expect(response.body).to eq "custom called" end end """ When I run `rspec spec` Then the examples should all pass @rails_pre_5 Scenario: Works with namespaced controllers Given a file named "spec/controllers/namespaced_controller_spec.rb" with: """ruby require "rails_helper" class ApplicationController < ActionController::Base; end module Outer module Inner class FoosController < ApplicationController; end end end RSpec.describe Outer::Inner::FoosController, :type => :controller do controller do def index @name = self.class.name @controller_name = controller_name render :text => "Hello World" end end it "creates anonymous controller derived from the namespace" do expect(controller).to be_a_kind_of(Outer::Inner::FoosController) end it "gets the class name as described" do expect{ get :index }.to change{ assigns[:name] }.to eq('Outer::Inner::FoosController') end it "gets the controller_name as described" do expect{ get :index }.to change{ assigns[:controller_name] }.to eq('foos') end end """ When I run `rspec spec` Then the examples should all pass @rails_post_5 Scenario: Works with namespaced controllers Given a file named "spec/controllers/namespaced_controller_spec.rb" with: """ruby require "rails_helper" class ApplicationController < ActionController::Base; end module Outer module Inner class FoosController < ApplicationController; end end end RSpec.describe Outer::Inner::FoosController, :type => :controller do controller do def index @name = self.class.name @controller_name = controller_name render :plain => "Hello World" end end it "creates anonymous controller derived from the namespace" do expect(controller).to be_a_kind_of(Outer::Inner::FoosController) end it "gets the class name as described" do expect{ get :index }.to change{ assigns[:name] }.to eq('Outer::Inner::FoosController') end it "gets the controller_name as described" do expect{ get :index }.to change{ assigns[:controller_name] }.to eq('foos') 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 "rails_helper" Rails.application.routes.draw do match "/login" => "sessions#new", :as => "login", :via => "get" end RSpec.describe ApplicationController, :type => :controller 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-3.7.2/features/controller_specs/bypass_rescue.feature000066400000000000000000000041221320451746500253770ustar00rootroot00000000000000Feature: 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 "rails_helper" require 'controllers/gadgets_controller_spec_context' RSpec.describe GadgetsController, :type => :controller 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 "rails_helper" require 'controllers/gadgets_controller_spec_context' RSpec.describe GadgetsController, :type => :controller 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-3.7.2/features/controller_specs/controller_spec.feature000066400000000000000000000051401320451746500257260ustar00rootroot00000000000000Feature: controller spec Scenario: simple passing example Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "rails_helper" RSpec.describe WidgetsController, :type => :controller 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 "rails_helper" RSpec.configure {|c| c.before { expect(controller).not_to be_nil }} RSpec.describe WidgetsController, :type => :controller do describe "GET index" do it "doesn't matter" do end end end """ When I run `rspec spec` Then the example should pass @rails_pre_5 Scenario: setting a different content type for example json (request type) Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "rails_helper" RSpec.describe WidgetsController, :type => :controller do describe "responds to" do it "responds to html by default" do post :create, { :widget => { :name => "Any Name" } } expect(response.content_type).to eq "text/html" end it "responds to custom formats when provided in the params" do post :create, { :widget => { :name => "Any Name" }, :format => :json } expect(response.content_type).to eq "application/json" end end end """ When I run `rspec spec` Then the example should pass @rails_post_5 Scenario: setting a different content type for example json (request type) Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "rails_helper" RSpec.describe WidgetsController, :type => :controller do describe "responds to" do it "responds to html by default" do post :create, :params => { :widget => { :name => "Any Name" } } expect(response.content_type).to eq "text/html" end it "responds to custom formats when provided in the params" do post :create, :params => { :widget => { :name => "Any Name" }, :format => :json } expect(response.content_type).to eq "application/json" end end end """ When I run `rspec spec` Then the example should pass rspec-rails-3.7.2/features/controller_specs/engine_routes.feature000066400000000000000000000027371320451746500254100ustar00rootroot00000000000000Feature: 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 "rails_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 RSpec.describe MyEngine::WidgetsController, :type => :controller 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-3.7.2/features/controller_specs/isolation_from_views.feature000066400000000000000000000060021320451746500267700ustar00rootroot00000000000000Feature: 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 "rails_helper" RSpec.describe WidgetsController, :type => :controller 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 "rails_helper" RSpec.describe WidgetsController, :type => :controller 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 "rails_helper" RSpec.describe ThingsController, :type => :controller 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 "rails_helper" RSpec.describe ThingsController, :type => :controller 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-3.7.2/features/controller_specs/render_views.feature000066400000000000000000000064141320451746500252320ustar00rootroot00000000000000Feature: 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 "rails_helper" RSpec.describe WidgetsController, :type => :controller do render_views describe "GET index" do it "has a widgets related heading" do get :index expect(response.body).to match /

.*widgets/im 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 "rails_helper" RSpec.describe WidgetsController, :type => :controller 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 /

.*widgets/im 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 /

.*widgets/im 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 "rails_helper" require "support/render_views" RSpec.describe WidgetsController, :type => :controller do describe "GET index" do it "renders the index template" do get :index expect(response.body).to match /

.*widgets/im end end end """ When I run `rspec spec` Then the examples should all pass rspec-rails-3.7.2/features/directory_structure.feature000066400000000000000000000155201320451746500233000ustar00rootroot00000000000000Feature: Directory Structure Specs are usually placed in a canonical directory structure that describes their purpose: - [Model specs](model-specs) reside in the `spec/models` directory - [Controller specs](controller-specs) reside in the `spec/controllers` directory - [Request specs](request-specs) reside in the `spec/requests` directory. The directory can also be named `integration` or `api`. - [Feature specs](feature-specs) reside in the `spec/features` directory - [View specs](view-specs) reside in the `spec/views` directory - [Helper specs](helper-specs) reside in the `spec/helpers` directory - [Mailer specs](mailer-specs) reside in the `spec/mailers` directory - [Routing specs](routing-specs) reside in the `spec/routing` directory - [Job specs](job-specs) reside in the `spec/jobs` directory - [System specs](system-specs) reside in the `spec/system` directory Application developers are free to use a different directory structure. In order to include the correct `rspec-rails` support functions, the specs need to have the appropriate corresponding metadata `:type` value: - Model specs: `type: :model` - Controller specs: `type: :controller` - Request specs: `type: :request` - Feature specs: `type: :feature` - View specs: `type: :view` - Helper specs: `type: :helper` - Mailer specs: `type: :mailer` - Routing specs: `type: :routing` - Job specs: `type: :job` - System specs: `type: :system` For example, say the spec for the `ThingsController` is located in `spec/legacy/things_controller_spec.rb`. Simply tag the spec's `RSpec.describe` block with the `type: :controller` metadata: ```ruby ​# spec/legacy/things_controller_spec.rb RSpec.describe ThingsController, type: :controller do describe "GET index" do ​# Examples end end ``` **Note:** Standard RSpec specs do not require any additional metadata by default. Check out the [`rspec-core`](/rspec/rspec-core/docs) documentation on [using metadata](/rspec/rspec-core/docs/metadata) for more details. Automatically Adding Metadata ----------------------------- RSpec versions before 3.0.0 automatically added metadata to specs based on their location on the filesystem. This was both confusing to new users and not desirable for some veteran users. In RSpec 3, this behavior must be explicitly enabled: ```ruby ​# spec/rails_helper.rb RSpec.configure do |config| config.infer_spec_type_from_file_location! end ``` Since this assumed behavior is so prevalent in tutorials, the default configuration generated by `rails generate rspec:install` enables this. If you follow the above listed canonical directory structure and have configured `infer_spec_type_from_file_location!`, RSpec will automatically include the correct support functions for each type. If you want to set metadata for a custom directory that doesn't follow fit the canonical structure above, you can do the following: ```ruby ​# set `:type` for serializers directory RSpec.configure do |config| config.define_derived_metadata(:file_path => Regexp.new('/spec/serializers/')) do |metadata| metadata[:type] = :serializer end end ``` Tips on Spec Location --------------------- It is suggested that the `spec/` directory structure generally mirror both `app/` and `lib/`. This makes it easy to locate corresponding code and spec files. **Example:** app ├── controllers │   ├── application_controller.rb │   └── books_controller.rb ├── helpers │   ├── application_helper.rb │   └── books_helper.rb ├── models │   ├── author.rb │   ├── book.rb └── views ├── books ├── layouts lib ├── country_map.rb ├── development_mail_interceptor.rb ├── enviroment_mail_interceptor.rb └── tasks ├── irc.rake spec ├── controllers │   ├── books_controller_spec.rb ├── country_map_spec.rb ├── features │   ├── tracking_book_delivery_spec.rb ├── helpers │   └── books_helper_spec.rb ├── models │   ├── author_spec.rb │   ├── book_spec.rb ├── rails_helper.rb ├── requests │   ├── books_spec.rb ├── routing │   └── books_routing_spec.rb ├── spec_helper.rb └── tasks │   ├── irc_spec.rb └── views ├── books Scenario: Standard Rails specs must specify the `:type` metadata Given a file named "spec/functional/widgets_controller_spec.rb" with: """ruby require "rails_helper" RSpec.describe WidgetsController, :type => :controller do it "responds successfully" do get :index expect(response.status).to eq(200) end end """ When I run `rspec spec` Then the example should pass Scenario: Non-rails related specs do not require `:type` metadata by default Given a file named "spec/ledger/entry_spec.rb" with: """ruby require "spec_helper" Entry = Struct.new(:description, :us_cents) RSpec.describe Entry do it "has a description" do is_expected.to respond_to(:description) end end """ When I run `rspec spec` Then the example should pass Scenario: Inferring spec type from the file location adds the appropriate metadata Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "rails_helper" RSpec.configure do |config| config.infer_spec_type_from_file_location! end RSpec.describe WidgetsController do it "responds successfully" do get :index expect(response.status).to eq(200) end end """ When I run `rspec spec` Then the example should pass Scenario: Specs in canonical directories can override their inferred types Given a file named "spec/routing/duckduck_routing_spec.rb" with: """ruby require "rails_helper" Rails.application.routes.draw do get "/example" => redirect("http://example.com") end RSpec.configure do |config| config.infer_spec_type_from_file_location! end # Due to limitations in the Rails routing test framework, routes that # perform redirects must actually be tested via request specs RSpec.describe "/example", :type => :request do it "redirects to example.com" do get "/example" expect(response).to redirect_to("http://example.com") end end """ When I run `rspec spec` Then the example should pass rspec-rails-3.7.2/features/feature_specs/000077500000000000000000000000001320451746500204245ustar00rootroot00000000000000rspec-rails-3.7.2/features/feature_specs/feature_spec.feature000066400000000000000000000060271320451746500244530ustar00rootroot00000000000000Feature: 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 are marked by `:type => :feature` or if you have set `config.infer_spec_type_from_file_location!` by placing them in `spec/features`. Feature specs require the [Capybara](http://github.com/jnicklas/capybara) gem, version 2.2.0 or later. We recommend version 2.4.0 or later to avoid some deprecation warnings and have support for [`config.expose_dsl_globally = false`](/rspec/rspec-core/docs/configuration/global-namespace-dsl). 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. Capybara is intended to simulate browser requests with HTTP. It will primarily send HTML content. 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](http://c2.com/cgi/wiki?CustomerTest) and [acceptance](http://c2.com/cgi/wiki?AcceptanceTest) tests. When capybara is required it sets `:type => :feature` automatically for you. @rails_pre_5.1 Scenario: Feature specs are skipped without Capybara Given a file named "spec/features/widget_management_spec.rb" with: """ruby require "rails_helper" RSpec.feature "Widget management", :type => :feature 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 exit status should be 0 And the output should contain "1 example, 0 failures, 1 pending" And the output should contain: """ Pending: (Failures listed here are expected and do not affect your suite's status) 1) Widget management User creates a new widget # Feature specs require the Capybara (http://github.com/jnicklas/capybara) gem, version 2.2.0 or later. We recommend version 2.4.0 or later to avoid some deprecation warnings and have support for `config.expose_dsl_globally = false`. # ./spec/features/widget_management_spec.rb:4 """ @capybara Scenario: specify creating a Widget by driving the application with capybara Given a file named "spec/features/widget_management_spec.rb" with: """ruby require "rails_helper" RSpec.feature "Widget management", :type => :feature do scenario "User creates a new widget" do visit "/widgets/new" 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-3.7.2/features/file_fixture.feature000066400000000000000000000021011320451746500216300ustar00rootroot00000000000000Feature: file fixture Rails 5 adds simple access to sample files called file fixtures. File fixtures are normal files stored in spec/fixtures/files by default. File fixtures are represented as +Pathname+ objects. This makes it easy to extract specific information: ```ruby file_fixture("example.txt").read # get the file's content file_fixture("example.mp3").size # get the file size ``` You can customize files location by setting ```ruby RSpec.configure do |config| config.file_fixture_path = "spec/custom_directory" end ``` Scenario: Reading file content from fixtures directory Given file fixtures are available And a file named "spec/fixtures/files/sample.txt" with: """ Hello """ And a file named "spec/lib/file_spec.rb" with: """ruby require "rails_helper" RSpec.describe "file" do it "reads sample file" do expect(file_fixture("sample.txt").read).to eq("Hello") end end """ When I run `rspec spec/lib/file_spec.rb` Then the examples should all pass rspec-rails-3.7.2/features/helper_specs/000077500000000000000000000000001320451746500202505ustar00rootroot00000000000000rspec-rails-3.7.2/features/helper_specs/helper_spec.feature000066400000000000000000000074131320451746500241230ustar00rootroot00000000000000Feature: helper spec Helper specs are marked by `:type => :helper` or if you have set `config.infer_spec_type_from_file_location!` by placing them in `spec/helpers`. 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 "rails_helper" RSpec.describe ApplicationHelper, :type => :helper 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 "rails_helper" RSpec.describe ApplicationHelper, :type => :helper 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 "rails_helper" RSpec.describe WidgetsHelper, :type => :helper 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 "rails_helper" RSpec.describe WidgetsHelper, :type => :helper 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-3.7.2/features/job_specs/000077500000000000000000000000001320451746500175435ustar00rootroot00000000000000rspec-rails-3.7.2/features/job_specs/job_spec.feature000066400000000000000000000102221320451746500227010ustar00rootroot00000000000000Feature: job spec Job specs provide alternative assertions to those available in `ActiveJob::TestHelper` and help assert behaviour of the jobs themselves and that other entities correctly enqueue them. Job specs are marked by `:type => :job` or if you have set `config.infer_spec_type_from_file_location!` by placing them in `spec/jobs`. With job specs, you can: * specify the job class which was enqueued * specify the arguments passed to the job * specify when the job was enqueued until * specify the queue which the job was enqueued to Check the documentation on [`have_been_enqueued`](matchers/have-been-enqueued-matcher) and [`have_enqueued_job`](matchers/have-enqueued-job-matcher) for more information. Background: Given active job is available Scenario: specify that job was enqueued Given a file named "spec/jobs/upload_backups_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob, :type => :job do describe "#perform_later" do it "uploads a backup" do ActiveJob::Base.queue_adapter = :test expect { UploadBackupsJob.perform_later('backup') }.to have_enqueued_job end end end """ When I run `rspec spec/jobs/upload_backups_spec.rb` Then the example should pass Scenario: specify that job was enqueued for the correct date and time Given a file named "spec/jobs/upload_backups_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob, :type => :job do describe "#perform_later" do it "uploads a backup" do ActiveJob::Base.queue_adapter = :test expect { UploadBackupsJob.set(wait_until: Date.tomorrow.noon, queue: "low").perform_later('backup') }.to have_enqueued_job.with('backup').on_queue("low").at(Date.tomorrow.noon) end end end """ When I run `rspec spec/jobs/upload_backups_spec.rb` Then the example should pass Scenario: specify that job was enqueued with alias block syntax Given a file named "spec/jobs/upload_backups_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob, :type => :job do describe "#perform_later" do it "uploads a backup" do ActiveJob::Base.queue_adapter = :test expect { UploadBackupsJob.perform_later('backup') }.to enqueue_job end end end """ When I run `rspec spec/jobs/upload_backups_spec.rb` Then the example should pass Scenario: specify that job was enqueued with imperative syntax Given a file named "spec/jobs/upload_backups_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob, :type => :job do describe "#perform_later" do it "uploads a backup" do ActiveJob::Base.queue_adapter = :test UploadBackupsJob.perform_later('backup') expect(UploadBackupsJob).to have_been_enqueued end end end """ When I run `rspec spec/jobs/upload_backups_spec.rb` Then the example should pass Scenario: specify that job was enqueued with imperative syntax and a chained expectation Given a file named "spec/jobs/upload_backups_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob, :type => :job do describe "#perform_later" do it "uploads a backup" do ActiveJob::Base.queue_adapter = :test UploadBackupsJob.perform_later('backup') expect(UploadBackupsJob).to have_been_enqueued.exactly(:once) end end end """ When I run `rspec spec/jobs/upload_backups_spec.rb` Then the example should pass Scenario: the test adapter must be set to :test Given a file named "spec/jobs/upload_backups_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob, :type => :job do describe "#perform_later" do it "uploads a backup" do ActiveJob::Base.queue_adapter = :development end end end """ When I run `rspec spec/jobs/upload_backups_spec.rb` Then the example should fail rspec-rails-3.7.2/features/mailer_specs/000077500000000000000000000000001320451746500202425ustar00rootroot00000000000000rspec-rails-3.7.2/features/mailer_specs/README.md000066400000000000000000000015001320451746500215150ustar00rootroot00000000000000By default Mailer specs reside in the `spec/mailers` folder. Adding the metadata `:type => :mailer` to any context makes its examples be treated as mailer specs. A mailer spec is a thin wrapper for an ActionMailer::TestCase, and includes all of the behavior and assertions that it provides, in addition to RSpec's own behavior and expectations. ## Examples require "rails_helper" RSpec.describe Notifications, :type => :mailer do describe "notify" do let(:mail) { Notifications.signup } it "renders the headers" do expect(mail.subject).to eq("Signup") expect(mail.to).to eq(["to@example.org"]) expect(mail.from).to eq(["from@example.com"]) end it "renders the body" do expect(mail.body.encoded).to match("Hi") end end end rspec-rails-3.7.2/features/mailer_specs/mailer_spec.feature000066400000000000000000000027711320451746500241110ustar00rootroot00000000000000Feature: mailer spec @rails_post_5 Scenario: simple passing example Given a file named "spec/mailers/notifications_mailer_spec.rb" with: """ruby require "rails_helper" RSpec.describe NotificationsMailer, :type => :mailer do describe "notify" do let(:mail) { NotificationsMailer.signup } it "renders the headers" do expect(mail.subject).to eq("Signup") expect(mail.to).to eq(["to@example.org"]) expect(mail.from).to eq(["from@example.com"]) end it "renders the body" do expect(mail.body.encoded).to match("Hi") end end end """ When I run `rspec spec` Then the example should pass @rails_pre_5 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 'rails_helper' RSpec.describe Notifications, :type => :mailer do let(:mail) { Notifications.signup } it "renders the headers" do expect(mail.subject).to eq("Signup") expect(mail.to).to eq(["to@example.org"]) expect(mail.from).to eq(["from@example.com"]) end it 'renders the body' do expect(mail.body.encoded).to match("Hi") end end """ When I run `rspec spec` Then the examples should all pass rspec-rails-3.7.2/features/mailer_specs/url_helpers.feature000066400000000000000000000051741320451746500241520ustar00rootroot00000000000000Feature: URL helpers in mailer examples Mailer specs are marked by `:type => :mailer` or if you have set `config.infer_spec_type_from_file_location!` by placing them in `spec/mailers`. @rails_post_5 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 'rails_helper' RSpec.describe NotificationsMailer, :type => :mailer 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 @rails_post_5 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 'rails_helper' RSpec.describe NotificationsMailer, :type => :mailer 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 @rails_pre_5 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 'rails_helper' RSpec.describe Notifications, :type => :mailer 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 @rails_pre_5 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 'rails_helper' RSpec.describe Notifications, :type => :mailer 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-3.7.2/features/matchers/000077500000000000000000000000001320451746500174025ustar00rootroot00000000000000rspec-rails-3.7.2/features/matchers/README.md000066400000000000000000000007371320451746500206700ustar00rootroot00000000000000rspec-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-3.7.2/features/matchers/have_been_enqueued_matcher.feature000066400000000000000000000045611320451746500262770ustar00rootroot00000000000000Feature: have_been_enqueued matcher The `have_been_enqueued` matcher is used to check if given ActiveJob job was enqueued. Background: Given active job is available Scenario: Checking job class name Given a file named "spec/jobs/upload_backups_job_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob do it "matches with enqueued job" do ActiveJob::Base.queue_adapter = :test UploadBackupsJob.perform_later expect(UploadBackupsJob).to have_been_enqueued end end """ When I run `rspec spec/jobs/upload_backups_job_spec.rb` Then the examples should all pass Scenario: Checking passed arguments to job Given a file named "spec/jobs/upload_backups_job_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob do it "matches with enqueued job" do ActiveJob::Base.queue_adapter = :test UploadBackupsJob.perform_later("users-backup.txt", "products-backup.txt") expect(UploadBackupsJob).to( have_been_enqueued.with("users-backup.txt", "products-backup.txt") ) end end """ When I run `rspec spec/jobs/upload_backups_job_spec.rb` Then the examples should all pass Scenario: Checking job enqueued time Given a file named "spec/jobs/upload_backups_job_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob do it "matches with enqueued job" do ActiveJob::Base.queue_adapter = :test UploadBackupsJob.set(:wait_until => Date.tomorrow.noon).perform_later expect(UploadBackupsJob).to have_been_enqueued.at(Date.tomorrow.noon) end end """ When I run `rspec spec/jobs/upload_backups_job_spec.rb` Then the examples should all pass Scenario: Checking job queue name Given a file named "spec/jobs/upload_backups_job_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob do it "matches with enqueued job" do ActiveJob::Base.queue_adapter = :test UploadBackupsJob.perform_later expect(UploadBackupsJob).to have_been_enqueued.on_queue("default") end end """ When I run `rspec spec/jobs/upload_backups_job_spec.rb` Then the examples should all pass rspec-rails-3.7.2/features/matchers/have_enqueued_job_matcher.feature000066400000000000000000000055741320451746500261450ustar00rootroot00000000000000Feature: have_enqueued_job matcher The `have_enqueued_job` (also aliased as `enqueue_job`) matcher is used to check if given ActiveJob job was enqueued. Background: Given active job is available Scenario: Checking job class name Given a file named "spec/jobs/upload_backups_job_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob do it "matches with enqueued job" do ActiveJob::Base.queue_adapter = :test expect { UploadBackupsJob.perform_later }.to have_enqueued_job(UploadBackupsJob) end end """ When I run `rspec spec/jobs/upload_backups_job_spec.rb` Then the examples should all pass Scenario: Checking passed arguments to job Given a file named "spec/jobs/upload_backups_job_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob do it "matches with enqueued job" do ActiveJob::Base.queue_adapter = :test expect { UploadBackupsJob.perform_later("users-backup.txt", "products-backup.txt") }.to have_enqueued_job.with("users-backup.txt", "products-backup.txt") end end """ When I run `rspec spec/jobs/upload_backups_job_spec.rb` Then the examples should all pass Scenario: Checking job enqueued time Given a file named "spec/jobs/upload_backups_job_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob do it "matches with enqueued job" do ActiveJob::Base.queue_adapter = :test expect { UploadBackupsJob.set(:wait_until => Date.tomorrow.noon).perform_later }.to have_enqueued_job.at(Date.tomorrow.noon) end end """ When I run `rspec spec/jobs/upload_backups_job_spec.rb` Then the examples should all pass Scenario: Checking job queue name Given a file named "spec/jobs/upload_backups_job_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob do it "matches with enqueued job" do ActiveJob::Base.queue_adapter = :test expect { UploadBackupsJob.perform_later }.to have_enqueued_job.on_queue("default") end end """ When I run `rspec spec/jobs/upload_backups_job_spec.rb` Then the examples should all pass Scenario: Using alias method Given a file named "spec/jobs/upload_backups_job_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob do it "matches with enqueued job" do ActiveJob::Base.queue_adapter = :test expect { UploadBackupsJob.perform_later }.to enqueue_job(UploadBackupsJob) end end """ When I run `rspec spec/jobs/upload_backups_job_spec.rb` Then the examples should all pass rspec-rails-3.7.2/features/matchers/have_http_status_matcher.feature000066400000000000000000000112031320451746500260440ustar00rootroot00000000000000Feature: `have_http_status` matcher The `have_http_status` matcher is used to specify that a response returns a desired status code. The matcher works on any `response` object. It is available for use in [controller specs](../controller-specs), [request specs](../request-specs), and [feature specs](../feature-specs). Scenario: Checking a numeric response code Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "rails_helper" RSpec.describe ApplicationController, :type => :controller do controller do def index render :json => {}, :status => 209 end end describe "GET #index" do it "returns a 209 custom status code" do get :index expect(response).to have_http_status(209) end end end """ When I run `rspec spec` Then the examples should all pass Scenario: Checking a symbolic response code Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "rails_helper" RSpec.describe ApplicationController, :type => :controller do controller do def index render :json => {}, :status => :see_other end end describe "GET #index" do it "returns a :see_other status code" do get :index expect(response).to have_http_status(:see_other) end end end """ When I run `rspec spec` Then the examples should all pass Scenario: Checking a general response code Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "rails_helper" RSpec.describe ApplicationController, :type => :controller do controller do def index render :json => {}, :status => :bad_gateway end end describe "GET #index" do it "returns a some type of error status code" do get :index expect(response).to have_http_status(:error) end end end """ When I run `rspec spec` Then the examples should all pass Scenario: Using in a controller spec Given a file named "spec/controllers/gadgets_spec.rb" with: """ruby require "rails_helper" RSpec.describe GadgetsController, :type => :controller do describe "GET #index" do it "returns a 200 OK status" do get :index expect(response).to have_http_status(:ok) end end end """ When I run `rspec spec/controllers/gadgets_spec.rb` Then the examples should all pass @rails_pre_5 Scenario: Using in a request spec Given a file named "spec/requests/gadgets/widget_management_spec.rb" with: """ruby require "rails_helper" RSpec.describe "Widget management", :type => :request do it "creates a Widget and redirects to the Widget's page" do get "/widgets/new" expect(response).to have_http_status(:ok) post "/widgets", :widget => {:name => "My Widget"} expect(response).to have_http_status(302) follow_redirect! expect(response).to have_http_status(:success) end end """ When I run `rspec spec/requests` Then the examples should all pass @rails_post_5 Scenario: Using in a request spec Given a file named "spec/requests/gadgets/widget_management_spec.rb" with: """ruby require "rails_helper" RSpec.describe "Widget management", :type => :request do it "creates a Widget and redirects to the Widget's page" do get "/widgets/new" expect(response).to have_http_status(:ok) post "/widgets", :params => { :widget => {:name => "My Widget"} } expect(response).to have_http_status(302) follow_redirect! expect(response).to have_http_status(:success) end end """ When I run `rspec spec/requests` Then the examples should all pass @capybara Scenario: Using in a feature spec Given a file named "spec/features/widget_management_spec.rb" with: """ruby require "rails_helper" RSpec.feature "Widget management", :type => :feature do scenario "User creates a new widget" do visit "/widgets/new" expect(page).to have_http_status(200) click_button "Create Widget" expect(page).to have_http_status(:success) end end """ When I run `rspec spec/features/widget_management_spec.rb` Then the example should pass rspec-rails-3.7.2/features/matchers/new_record_matcher.feature000066400000000000000000000022141320451746500246100ustar00rootroot00000000000000Feature: 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 "rails_helper" RSpec.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-3.7.2/features/matchers/redirect_to_matcher.feature000066400000000000000000000047071320451746500247750ustar00rootroot00000000000000Feature: 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). @rails_pre_5 Scenario: redirect_to with four possible options Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "rails_helper" RSpec.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 @rails_post_5 Scenario: redirect_to with four possible options Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "rails_helper" RSpec.describe WidgetsController do describe "#create" do subject { post :create, :params => { :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-3.7.2/features/matchers/relation_match_array.feature000066400000000000000000000015311320451746500251460ustar00rootroot00000000000000Feature: 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 "rails_helper" RSpec.describe Widget do let!(:widgets) { Array.new(3) { Widget.create } } if ::Rails::VERSION::STRING >= '4' subject { Widget.all } else subject { Widget.scoped } end 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-3.7.2/features/matchers/render_template_matcher.feature000066400000000000000000000035751320451746500256460ustar00rootroot00000000000000Feature: 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 "rails_helper" RSpec.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 it "does not render a different template" do expect(subject).to_not render_template("gadgets/show") 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 "rails_helper" RSpec.describe "gadgets/index" do it "renders the index template" do assign(:gadgets, [Gadget.create!]) render expect(view).to render_template(:index) expect(view).to render_template("index") expect(view).to render_template("gadgets/index") end it "does not render a different template" do expect(view).to_not render_template("gadgets/show") end end """ When I run `rspec spec/views` Then the examples should all pass rspec-rails-3.7.2/features/model_specs/000077500000000000000000000000001320451746500200715ustar00rootroot00000000000000rspec-rails-3.7.2/features/model_specs/README.md000066400000000000000000000014101320451746500213440ustar00rootroot00000000000000Model specs are marked by `:type => :model` or if you have set `config.infer_spec_type_from_file_location!` by placing them in `spec/models`. 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 "rails_helper" RSpec.describe Post, :type => :model 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-3.7.2/features/model_specs/transactional_examples.feature000066400000000000000000000054541320451746500262160ustar00rootroot00000000000000Feature: 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 "rails_helper" RSpec.describe Widget, :type => :model 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 "rails_helper" RSpec.configure do |c| c.use_transactional_examples = true end RSpec.describe Widget, :type => :model 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 "rails_helper" RSpec.configure do |c| c.use_transactional_examples = false c.order = "defined" end RSpec.describe Widget, :type => :model 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 "rails_helper" RSpec.describe Thing, :type => :model 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-3.7.2/features/model_specs/verified_doubles.feature000066400000000000000000000010761320451746500247640ustar00rootroot00000000000000Feature: verified doubles By default rspec verified doubles dont support dynamic methods on `instance_double`. `rspec-rails` enabled this support for column methods through an extension. Scenario: Given a file named "spec/models/widget_spec.rb" with: """ruby require "rails_helper" RSpec.describe Widget, :type => :model do it "has one after adding one" do instance_double("Widget", :name => "my name") end end """ When I run `rspec spec/models/widget_spec.rb` Then the examples should all pass rspec-rails-3.7.2/features/request_specs/000077500000000000000000000000001320451746500204615ustar00rootroot00000000000000rspec-rails-3.7.2/features/request_specs/request_spec.feature000066400000000000000000000134201320451746500245400ustar00rootroot00000000000000Feature: 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). Request specs are marked by `:type => :request` or if you have set `config.infer_spec_type_from_file_location!` by placing them in `spec/requests`. 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). @rails_pre_5 Scenario: specify managing a Widget with Rails integration methods Given a file named "spec/requests/widget_management_spec.rb" with: """ruby require "rails_helper" RSpec.describe "Widget management", :type => :request 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 it "does not render a different template" do get "/widgets/new" expect(response).to_not render_template(:show) end end """ When I run `rspec spec/requests/widget_management_spec.rb` Then the example should pass @rails_post_5 Scenario: specify managing a Widget with Rails integration methods Given a file named "spec/requests/widget_management_spec.rb" with: """ruby require "rails_helper" RSpec.describe "Widget management", :type => :request do it "creates a Widget and redirects to the Widget's page" do get "/widgets/new" expect(response).to render_template(:new) post "/widgets", :params => { :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 it "does not render a different template" do get "/widgets/new" expect(response).to_not render_template(:show) end end """ When I run `rspec spec/requests/widget_management_spec.rb` Then the example should pass @unsupported-on-rails-3-0 @rails_pre_5 Scenario: requesting a JSON response Given a file named "spec/requests/widget_management_spec.rb" with: """ruby require "rails_helper" RSpec.describe "Widget management", :type => :request do it "creates a Widget" do headers = { "ACCEPT" => "application/json", # This is what Rails 4 accepts "HTTP_ACCEPT" => "application/json" # This is what Rails 3 accepts } post "/widgets", { :widget => {:name => "My Widget"} }, headers expect(response.content_type).to eq("application/json") expect(response).to have_http_status(:created) end end """ When I run `rspec spec/requests/widget_management_spec.rb` Then the example should pass @rails_post_5 Scenario: requesting a JSON response Given a file named "spec/requests/widget_management_spec.rb" with: """ruby require "rails_helper" RSpec.describe "Widget management", :type => :request do it "creates a Widget" do headers = { "ACCEPT" => "application/json", # This is what Rails 4 accepts "HTTP_ACCEPT" => "application/json" # This is what Rails 3 accepts } post "/widgets", :params => { :widget => {:name => "My Widget"} }, :headers => headers expect(response.content_type).to eq("application/json") expect(response).to have_http_status(:created) end end """ When I run `rspec spec/requests/widget_management_spec.rb` Then the example should pass @rails_pre_5 Scenario: providing JSON data Given a file named "spec/requests/widget_management_spec.rb" with: """ruby require "rails_helper" RSpec.describe "Widget management", :type => :request do it "creates a Widget and redirects to the Widget's page" do headers = { "CONTENT_TYPE" => "application/json" } post "/widgets", '{ "widget": { "name":"My Widget" } }', headers expect(response).to redirect_to(assigns(:widget)) end end """ When I run `rspec spec/requests/widget_management_spec.rb` Then the example should pass @rails_post_5 Scenario: providing JSON data Given a file named "spec/requests/widget_management_spec.rb" with: """ruby require "rails_helper" RSpec.describe "Widget management", :type => :request do it "creates a Widget and redirects to the Widget's page" do headers = { "CONTENT_TYPE" => "application/json" } post "/widgets", :params => '{ "widget": { "name":"My Widget" } }', :headers => headers expect(response).to redirect_to(assigns(:widget)) end end """ When I run `rspec spec/requests/widget_management_spec.rb` Then the example should pass rspec-rails-3.7.2/features/routing_specs/000077500000000000000000000000001320451746500204605ustar00rootroot00000000000000rspec-rails-3.7.2/features/routing_specs/README.md000066400000000000000000000012301320451746500217330ustar00rootroot00000000000000Routing specs are marked by `:type => :routing` or if you have set `config.infer_spec_type_from_file_location!` by placing them in `spec/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-3.7.2/features/routing_specs/be_routable_matcher.feature000066400000000000000000000051141320451746500260240ustar00rootroot00000000000000Feature: 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 "rails_helper" RSpec.describe "routes for Widgets", :type => :routing 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 "rails_helper" RSpec.describe "routes for Widgets", :type => :routing 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 "rails_helper" RSpec.describe "routes for Widgets", :type => :routing 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 "rails_helper" RSpec.describe "routes for Widgets", :type => :routing 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 "rails_helper" RSpec.describe WidgetsController, :type => :routing 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-3.7.2/features/routing_specs/engine_routes.feature000066400000000000000000000020501320451746500247000ustar00rootroot00000000000000Feature: 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 "rails_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 RSpec.describe MyEngine::WidgetsController, :type => :routing 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-3.7.2/features/routing_specs/named_routes.feature000066400000000000000000000010261320451746500245210ustar00rootroot00000000000000Feature: 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 "rails_helper" RSpec.describe "routes to the widgets controller", :type => :routing 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-3.7.2/features/routing_specs/route_to_matcher.feature000066400000000000000000000055701320451746500254070ustar00rootroot00000000000000Feature: 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 "rails_helper" RSpec.describe "routes for Widgets", :type => :routing 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 "rails_helper" RSpec.describe "routes for Widgets", :type => :routing 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 "rails_helper" RSpec.describe "routes for Widgets", :type => :routing 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 "rails_helper" RSpec.describe "routes for Widgets", :type => :routing 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 "rails_helper" RSpec.describe "routes for Widgets", :type => :routing 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-3.7.2/features/step_definitions/000077500000000000000000000000001320451746500211425ustar00rootroot00000000000000rspec-rails-3.7.2/features/step_definitions/additional_cli_steps.rb000066400000000000000000000013411320451746500256430ustar00rootroot00000000000000begin require "active_job" rescue LoadError # rubocop:disable Lint/HandleExceptions end require "rails/version" require "rspec/rails/feature_check" Then /^the example(s)? should( all)? pass$/ do |_, _| step %q{the output should contain "0 failures"} step %q{the exit status should be 0} end Then /^the example(s)? should( all)? fail/ do |_, _| step %q{the output should not contain "0 failures"} step %q{the exit status should not be 0} end Given /active job is available/ do if !RSpec::Rails::FeatureCheck.has_active_job? pending "ActiveJob is not available" end end Given /file fixtures are available/ do if !RSpec::Rails::FeatureCheck.has_file_fixture? pending "file fixtures are not available" end end rspec-rails-3.7.2/features/support/000077500000000000000000000000001320451746500173105ustar00rootroot00000000000000rspec-rails-3.7.2/features/support/capybara.rb000066400000000000000000000006021320451746500214150ustar00rootroot00000000000000Around "@capybara" do |scenario, block| # We are caught in a weird situation here. rspec-rails supports 1.8.7 and # above, but capybara beyond a certain version only supports 1.9.3 and above. # On 1.8.7 and 1.9.2, we run most of the rspec-rails test suite but leave out # parts that require capybara. if RUBY_VERSION >= '1.9.3' require 'capybara' block.call end end rspec-rails-3.7.2/features/support/env.rb000066400000000000000000000024711320451746500204310ustar00rootroot00000000000000require 'aruba/cucumber' require 'fileutils' module ArubaExt def run(cmd, timeout = nil) exec_cmd = cmd =~ /^rspec/ ? "bin/#{cmd}" : cmd super(exec_cmd, timeout) end # This method over rides Aruba 0.5.4 implementation so that we can reset Bundler to use the sample app Gemfile def in_current_dir(&block) Bundler.with_clean_env do _mkdir(current_dir) Dir.chdir(current_dir, &block) end end end World(ArubaExt) Before do @aruba_timeout_seconds = 30 end unless File.directory?('./tmp/example_app') system "rake generate:app generate:stuff" end Before do example_app_dir = 'tmp/example_app' # Per default Aruba will create a directory tmp/aruba where it performs its file operations. # https://github.com/cucumber/aruba/blob/v0.6.1/README.md#use-a-different-working-directory aruba_dir = 'tmp/aruba' # Remove the previous aruba workspace. FileUtils.rm_rf(aruba_dir) if File.exist?(aruba_dir) # We want fresh `example_app` project with empty `spec` dir except helpers. # FileUtils.cp_r on Ruby 1.9.2 doesn't preserve permissions. system('cp', '-r', example_app_dir, aruba_dir) helpers = %w[spec/spec_helper.rb spec/rails_helper.rb] Dir["#{aruba_dir}/spec/*"].each do |path| next if helpers.any? { |helper| path.end_with?(helper) } FileUtils.rm_rf(path) end end rspec-rails-3.7.2/features/support/rails_versions.rb000066400000000000000000000002121320451746500226720ustar00rootroot00000000000000Around "@unsupported-on-rails-3-0" do |scenario, block| require 'rails' block.call unless ::Rails.version.to_s.start_with?("3.0") end rspec-rails-3.7.2/features/support/rubinius.rb000066400000000000000000000003411320451746500214730ustar00rootroot00000000000000# Required until https://github.com/rubinius/rubinius/issues/2430 is resolved ENV['RBXOPT'] = "#{ENV['RBXOPT']} -Xcompiler.no_rbc" Around "@unsupported-on-rbx" do |scenario, block| block.call unless defined?(Rubinius) end rspec-rails-3.7.2/features/system_specs/000077500000000000000000000000001320451746500203155ustar00rootroot00000000000000rspec-rails-3.7.2/features/system_specs/system_specs.feature000066400000000000000000000023061320451746500244140ustar00rootroot00000000000000Feature: System spec System specs are RSpec's wrapper around Rails' own [system tests](http://guides.rubyonrails.org/testing.html#system-testing). We encourage you to familiarse yourself with their documentation. RSpec **does not** use your `ApplicationSystemTestCase` helper. Instead it uses the default `driven_by(:selenium)` from Rails. If you want to override this behaviour you can call `driven_by` manually in a test. @system_test Scenario: System specs Given a file named "spec/system/widget_system_spec.rb" with: """ruby require "rails_helper" RSpec.describe "Widget management", :type => :system do before do driven_by(:rack_test) end it "enables me to create widgets" 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/system/widget_system_spec.rb` Then the exit status should be 0 And the output should contain "1 example, 0 failures" rspec-rails-3.7.2/features/upgrade/000077500000000000000000000000001320451746500172235ustar00rootroot00000000000000rspec-rails-3.7.2/features/upgrade/README.md000066400000000000000000000147471320451746500205170ustar00rootroot00000000000000# Upgrading from rspec-rails-2.x to rspec-rails-3 For detailed information on the general RSpec 3.x upgrade process see the [RSpec Upgrade docs](https://relishapp.com/rspec/docs/upgrade). There are several changes specific to `rspec-rails` to be aware of: - [Default helper files created in RSpec 3.x have changed](#default-helper-files) - [File-type inference disabled by default](#file-type-inference-disabled) - [Rails 4.x `ActiveRecord::Migration` pending migration checks](#pending-migration-checks) - [Extraction of `stub_model` and `mock_model` to `rspec-activemodel-mocks`](#extract-stub-model) ## Default helper files created in RSpec 3.x have changed In prior versions, only a single `spec_helper.rb` file was generated. This file has been moved to `rails_helper.rb`. The new `spec_helper.rb` is the same standard helper generated by running `rspec --init`. This change was made to accomplish two general goals: - Keep the installation process in sync with regular RSpec changes - Provide an out-of-the-box way to avoid loading Rails for those specs that do not require it ### Generators Generators run in RSpec 3.x will require `rails_helper` and not `spec_helper`. ### Upgrading an Existing App For most existing apps, one of the following upgrade paths is sufficient to switch to the new helpers: #### I need to move things over in stages 1. Create a new `rails_helper.rb` with the following content: ```ruby require 'spec_helper' ``` 2. As necessary, replace `require 'spec_helper'` with `require 'rails_helper'` in the specs. 3. When ready, move any Rails specific code and setup from `spec_helper.rb` to `rails_helper.rb`. #### I'm ready to just switch completely 1. Move the existing `spec_helper.rb` to `rails_helper.rb`: ```ruby git mv spec/spec_helper.rb spec/rails_helper.rb ``` 2. Run the installation rake task opting to not replace `rails_helper.rb`: ```console $ bin/rails generate rspec:install create .rspec exist spec create spec/spec_helper.rb conflict spec/rails_helper.rb Overwrite my_app/spec/rails_helper.rb? (enter "h"for help) [Ynaqdh] n skip spec/rails_helper.rb ``` 3. Move any non-Rails RSpec configurations and customizations from your `rails_helper.rb` to `spec_helper.rb`. 4. Find/replace instances of `require 'spec_helper'` with `require 'rails_helper'` in any specs which rely on Rails. ## File-type inference disabled by default Previously we automatically inferred spec type from a file location, this was a surprising behaviour for new users and undesirable for some veteran users so from RSpec 3 onwards this behaviour must be explicitly opted into with: ```Ruby RSpec.configure do |config| config.infer_spec_type_from_file_location! end ``` This change was made to accomplish our general goals of acting with the principle of least surprise and making RSpec configuration more explicit. See [the directory structure documentation](https://www.relishapp.com/rspec/rspec-rails/v/3-0/docs/directory-structure) for more details. ## Rails 4.x `ActiveRecord::Migration` pending migration checks If you are not using `ActiveRecord` you do not need to worry about these settings. Users of Rails 4.x can now take advantage of improved schema migration and sync abilities. Prior to RSpec 3, users were required to manually run migrations in both the development and test environments. Additionally, the behavior differed depending on if the specs were run via `rake` or via the standalone `rspec` command. With the release of Rails 4, new APIs have been exposed on `ActiveRecord::Migration`. This allows RSpec to take advantage of these new standard migration checks, mirroring behavior across the board. - Rails 4.0.x Add the following to the top of the `rails_helper` file after Rails has been required: ```ruby ActiveRecord::Migration.check_pending! ``` This will raise an exception if there are any pending schema changes. Users will still be required to manually keep the development and test environments in sync. - Rails 4.1+ With this release there was an exciting new feature. Users no longer need to keep the development and test environments in sync. To take advantage of this add the following to the top of the `rails_helper` file after Rails has been required: ```ruby ActiveRecord::Migration.maintain_test_schema! ``` What this does is that rather than just raising when the test schema has pending migrations, Rails will try to load the schema. An exception will now only be raised if there are pending migrations afterwards the schema has been loaded. There are a few caveates to be aware of when using this: - Migrations still need to be run manually; although now this only has to be done in the 'development' environment - An exception will be raised If the schema has not been initialized. The exception will provide instructions stating `rake db:migrate` needs to be run. It is possible to opt-out of checking for pending migrations. Since this is actually a feature of Rails, the change needs to be done as part of the Rails configuration. To do this, add the following to your `config/environments/test.rb` file: ```ruby config.active_record.maintain_test_schema = false ``` New RSpec projects don't need to worry about these commands as the `rails generate rspec:install` will add them automatically. ## Extraction of `stub_model` and `mock_model` to [`rspec-activemodel-mocks`](https://github.com/rspec/rspec-activemodel-mocks) Historically, `stub_model` and `mock_model` have been difficult to maintain. They are tightly coupled to `ActiveRecord` which isn't always the ORM of choice. This maintainence coupling has lead to delays with previous releases. Additionally, the objects generated by these methods hide important `ActiveRecord` behavior complexity which would otherwise be good to expose. Some alternatives are: - Wrap calls to `ActiveRecord` objects in more specific domain models and services - Use new unsaved `ActiveRecord` instances (e.g. `Model.new`) - Consider [partial mocks](https://www.relishapp.com/rspec/rspec-mocks/docs/basics/partial-test-doubles) on an `ActiveRecord` instance - Let the specs hit database directly where appropriate rspec-rails-3.7.2/features/upgrade/from_1x_to_2x.md000066400000000000000000000074551320451746500222460ustar00rootroot00000000000000# 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-3.7.2/features/view_specs/000077500000000000000000000000001320451746500177435ustar00rootroot00000000000000rspec-rails-3.7.2/features/view_specs/inferred_controller_path.feature000066400000000000000000000025131320451746500263760ustar00rootroot00000000000000Feature: 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 "rails_helper" RSpec.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 "rails_helper" RSpec.describe "widgets/new" do it "infers the controller action" 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 "rails_helper" RSpec.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-3.7.2/features/view_specs/stub_template.feature000066400000000000000000000031101320451746500241630ustar00rootroot00000000000000Feature: 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 "rails_helper" RSpec.describe "gadgets/list" do it "renders the gadget partial for each gadget" do assign(:gadgets, [ double(:name => "First"), double(: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 "rails_helper" RSpec.describe "gadgets/edit" do before(:each) do @gadget = assign(:gadget, Gadget.create!) 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-3.7.2/features/view_specs/view_spec.feature000066400000000000000000000167351320451746500233200ustar00rootroot00000000000000Feature: view spec View specs live in spec/views and render view templates in isolation. Scenario: View specs render the described view file Given a file named "spec/views/widgets/index.html.erb_spec.rb" with: """ruby require "rails_helper" RSpec.describe "widgets/index" do it "displays all the widgets" do assign(:widgets, [ Widget.create!(:name => "slicer"), Widget.create!(: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: View specs can have before block and nesting Given a file named "spec/views/widgets/index.html.erb_spec.rb" with: """ruby require "rails_helper" RSpec.describe "widgets/index" do context "with 2 widgets" do before(:each) do assign(:widgets, [ Widget.create!(:name => "slicer"), Widget.create!(: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: View specs can explicitly render templates Given a file named "spec/views/widgets/widget.html.erb_spec.rb" with: """ruby require "rails_helper" RSpec.describe "rendering the widget template" do it "displays the widget" do assign(:widget, Widget.create!(: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: View specs can have description that includes the format and handler Given a file named "spec/views/widgets/widget.xml.erb_spec.rb" with: """ruby require "rails_helper" RSpec.describe "widgets/widget.html.erb" do it "renders the HTML template" do render expect(rendered).to match /HTML/ end end RSpec.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: View specs can render locals in a partial Given a file named "spec/views/widgets/_widget.html.erb_spec.rb" with: """ruby require "rails_helper" RSpec.describe "rendering locals in a partial" do it "displays the widget" do widget = Widget.create!(: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: View specs can render locals in an implicit partial Given a file named "spec/views/widgets/_widget.html.erb_spec.rb" with: """ruby require "rails_helper" RSpec.describe "rendering locals in a partial" do it "displays the widget" do widget = Widget.create!(: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 @rails_pre_5 Scenario: View specs can render text Given a file named "spec/views/widgets/direct.html.erb_spec.rb" with: """ruby require "rails_helper" RSpec.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 @rails_post_5 Scenario: View specs can render text Given a file named "spec/views/widgets/direct.html.erb_spec.rb" with: """ruby require "rails_helper" RSpec.describe "rendering text directly" do it "displays the given text" do render :plain => "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: View specs can stub a helper method Given a file named "app/helpers/application_helper.rb" with: """ruby module ApplicationHelper def admin? false end end """ And 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 'rails_helper' RSpec.describe 'secrets/index' do before do allow(view).to receive(: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: View specs use symbols for keys in `request.path_parameters` to match Rails style Given a file named "spec/views/widgets/index.html.erb_spec.rb" with: """ruby require "rails_helper" RSpec.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 Scenario: View spec actions that do not require extra parameters have `request.fullpath` set Given a file named "spec/views/widgets/index.html.erb_spec.rb" with: """ruby require "rails_helper" RSpec.describe "widgets/index" do it "has a request.fullpath that is defined" do expect(controller.request.fullpath).to eq widgets_path end end """ When I run `rspec spec/views` Then the examples should all pass Scenario: View spec actions that require extra parameters have `request.fullpath` set when the developer supplies them Given a file named "spec/views/widgets/show.html.erb_spec.rb" with: """ruby require "rails_helper" RSpec.describe "widgets/show" do it "displays the widget with id: 1" do widget = Widget.create!(:name => "slicer") controller.extra_params = { :id => widget.id } expect(controller.request.fullpath).to eq widget_path(widget) end end """ When I run `rspec spec/views` Then the examples should all pass rspec-rails-3.7.2/lib/000077500000000000000000000000001320451746500145245ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/000077500000000000000000000000001320451746500166755ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec.rb000066400000000000000000000020161320451746500203350ustar00rootroot00000000000000require 'rails/generators/named_base' require 'rspec/rails/feature_check' # @private # Weirdly named generators namespace (should be `RSpec`) for compatability with # rails loading. module Rspec # @private module Generators # @private class Base < ::Rails::Generators::NamedBase include RSpec::Rails::FeatureCheck def self.source_root(path = nil) if path @_rspec_source_root = path else @_rspec_source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'rspec', generator_name, 'templates')) end end if ::Rails::VERSION::STRING < '3.1' def module_namespacing yield if block_given? end end end end end # @private module Rails module Generators # @private class GeneratedAttribute def input_type @input_type ||= if type == :text "textarea" else "input" end end end end end rspec-rails-3.7.2/lib/generators/rspec/000077500000000000000000000000001320451746500200115ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/controller/000077500000000000000000000000001320451746500221745ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/controller/controller_generator.rb000066400000000000000000000021271320451746500267540ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators # @private 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-3.7.2/lib/generators/rspec/controller/templates/000077500000000000000000000000001320451746500241725ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/controller/templates/controller_spec.rb000066400000000000000000000005361320451746500277200ustar00rootroot00000000000000require 'rails_helper' <% module_namespacing do -%> RSpec.describe <%= class_name %>Controller, <%= type_metatag(:controller) %> do <% for action in actions -%> describe "GET #<%= action %>" do it "returns http success" do get :<%= action %> expect(response).to have_http_status(:success) end end <% end -%> end <% end -%> rspec-rails-3.7.2/lib/generators/rspec/controller/templates/view_spec.rb000066400000000000000000000003131320451746500265000ustar00rootroot00000000000000require 'rails_helper' RSpec.describe "<%= file_name %>/<%= @action %>.html.<%= options[:template_engine] %>", <%= type_metatag(:view) %> do pending "add some examples to (or delete) #{__FILE__}" end rspec-rails-3.7.2/lib/generators/rspec/feature/000077500000000000000000000000001320451746500214445ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/feature/feature_generator.rb000066400000000000000000000014461320451746500254770ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators # @private class FeatureGenerator < Base class_option :feature_specs, :type => :boolean, :default => true, :desc => "Generate feature specs" class_option :singularize, :type => :boolean, :default => false, :desc => "Singularize the generated feature" def generate_feature_spec return unless options[:feature_specs] template template_name, File.join('spec/features', class_path, filename) end def template_name options[:singularize] ? 'feature_singular_spec.rb' : 'feature_spec.rb' end def filename if options[:singularize] "#{table_name.singularize}_spec.rb" else "#{table_name}_spec.rb" end end end end end rspec-rails-3.7.2/lib/generators/rspec/feature/templates/000077500000000000000000000000001320451746500234425ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/feature/templates/feature_singular_spec.rb000066400000000000000000000002431320451746500303370ustar00rootroot00000000000000require 'rails_helper' RSpec.feature "<%= class_name.singularize %>", <%= type_metatag(:feature) %> do pending "add some scenarios (or delete) #{__FILE__}" end rspec-rails-3.7.2/lib/generators/rspec/feature/templates/feature_spec.rb000066400000000000000000000002411320451746500264310ustar00rootroot00000000000000require 'rails_helper' RSpec.feature "<%= class_name.pluralize %>", <%= type_metatag(:feature) %> do pending "add some scenarios (or delete) #{__FILE__}" end rspec-rails-3.7.2/lib/generators/rspec/helper/000077500000000000000000000000001320451746500212705ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/helper/helper_generator.rb000066400000000000000000000006051320451746500251430ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators # @private 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-3.7.2/lib/generators/rspec/helper/templates/000077500000000000000000000000001320451746500232665ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/helper/templates/helper_spec.rb000066400000000000000000000010111320451746500260750ustar00rootroot00000000000000require 'rails_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 # expect(helper.concat_strings("this","that")).to eq("this that") # end # end # end <% module_namespacing do -%> RSpec.describe <%= class_name %>Helper, <%= type_metatag(:helper) %> do pending "add some examples to (or delete) #{__FILE__}" end <% end -%> rspec-rails-3.7.2/lib/generators/rspec/install/000077500000000000000000000000001320451746500214575ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/install/install_generator.rb000066400000000000000000000032451320451746500255240ustar00rootroot00000000000000require "rspec/support" require "rspec/core" RSpec::Support.require_rspec_core "project_initializer" require "rspec/rails/feature_check" module Rspec module Generators # @private class InstallGenerator < ::Rails::Generators::Base desc < tmpdir, :report_stream => StringIO.new ) initializer.run spec_helper_path = File.join(tmpdir, 'spec', 'spec_helper.rb') replace_generator_command(spec_helper_path) remove_warnings_configuration(spec_helper_path) end def replace_generator_command(spec_helper_path) gsub_file spec_helper_path, 'rspec --init', 'rails generate rspec:install', :verbose => false end def remove_warnings_configuration(spec_helper_path) empty_line = '^\n' comment_line = '^\s*#.+\n' gsub_file spec_helper_path, /#{empty_line}(#{comment_line})+\s+config\.warnings = true\n/, '', :verbose => false end end end end rspec-rails-3.7.2/lib/generators/rspec/install/templates/000077500000000000000000000000001320451746500234555ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/install/templates/spec/000077500000000000000000000000001320451746500244075ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/install/templates/spec/rails_helper.rb000066400000000000000000000057431320451746500274160ustar00rootroot00000000000000# This file is copied to spec/ when you run 'rails generate rspec:install' require 'spec_helper' ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) # Prevent database truncation if the environment is production abort("The Rails environment is running in production mode!") if Rails.env.production? require 'rspec/rails' # Add additional requires below this line. Rails is not loaded until this point! # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. # # The following line is provided for convenience purposes. It has the downside # of increasing the boot-up time by auto-requiring all files in the support # directory. Alternatively, in the individual `*_spec.rb` files, manually # require only the support files necessary. # # Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } <% if RSpec::Rails::FeatureCheck.can_maintain_test_schema? -%> # Checks for pending migrations and applies them before tests are run. # If you are not using ActiveRecord, you can remove this line. ActiveRecord::Migration.maintain_test_schema! <% elsif RSpec::Rails::FeatureCheck.can_check_pending_migrations? -%> # Checks for pending migrations before tests are run. # If you are not using ActiveRecord, you can remove this line. ActiveRecord::Migration.check_pending! <% end -%> RSpec.configure do |config| <% if RSpec::Rails::FeatureCheck.has_active_record? -%> # 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 <% end -%> # RSpec Rails can automatically mix in different behaviours to your tests # based on their file location, for example enabling you to call `get` and # `post` in specs under `spec/controllers`. # # You can disable this behaviour by removing the line below, and instead # explicitly tag your specs with their type, e.g.: # # RSpec.describe UsersController, :type => :controller do # # ... # end # # The different available types are documented in the features, such as in # https://relishapp.com/rspec/rspec-rails/docs config.infer_spec_type_from_file_location! # Filter lines from Rails gems in backtraces. config.filter_rails_from_backtrace! # arbitrary gems may also be filtered via: # config.filter_gems_from_backtrace("gem name") end rspec-rails-3.7.2/lib/generators/rspec/integration/000077500000000000000000000000001320451746500223345ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/integration/integration_generator.rb000066400000000000000000000011441320451746500272520ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators # @private class IntegrationGenerator < Base # Add a deprecation for this class, before rspec-rails 4, to use the # `RequestGenerator` instead class_option :request_specs, :type => :boolean, :default => true, :desc => "Generate request specs" def generate_request_spec return unless options[:request_specs] template 'request_spec.rb', File.join('spec/requests', class_path, "#{table_name}_spec.rb") end end end end rspec-rails-3.7.2/lib/generators/rspec/integration/templates/000077500000000000000000000000001320451746500243325ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/integration/templates/request_spec.rb000066400000000000000000000004421320451746500273610ustar00rootroot00000000000000require 'rails_helper' RSpec.describe "<%= class_name.pluralize %>", <%= type_metatag(:request) %> do describe "GET /<%= table_name %>" do it "works! (now write some real specs)" do get <%= index_helper %>_path expect(response).to have_http_status(200) end end end rspec-rails-3.7.2/lib/generators/rspec/job/000077500000000000000000000000001320451746500205635ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/job/job_generator.rb000066400000000000000000000004031320451746500237250ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators # @private class JobGenerator < Base def create_job_spec template 'job_spec.rb.erb', File.join('spec/jobs', class_path, "#{file_name}_job_spec.rb") end end end end rspec-rails-3.7.2/lib/generators/rspec/job/templates/000077500000000000000000000000001320451746500225615ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/job/templates/job_spec.rb.erb000066400000000000000000000002771320451746500254470ustar00rootroot00000000000000require 'rails_helper' <% module_namespacing do -%> RSpec.describe <%= class_name %>Job, <%= type_metatag(:job) %> do pending "add some examples to (or delete) #{__FILE__}" end <% end -%> rspec-rails-3.7.2/lib/generators/rspec/mailer/000077500000000000000000000000001320451746500212625ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/mailer/mailer_generator.rb000066400000000000000000000014761320451746500251360ustar00rootroot00000000000000require 'generators/rspec' require "rspec/rails/feature_check" module Rspec module Generators # @private 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 def generate_preview_files return unless RSpec::Rails::FeatureCheck.has_action_mailer_preview? template "preview.rb", File.join("spec/mailers/previews", class_path, "#{file_name}_preview.rb") end end end end rspec-rails-3.7.2/lib/generators/rspec/mailer/templates/000077500000000000000000000000001320451746500232605ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/mailer/templates/fixture000066400000000000000000000001101320451746500246610ustar00rootroot00000000000000<%= class_name %>#<%= @action %> Hi, find me in app/views/<%= @path %> rspec-rails-3.7.2/lib/generators/rspec/mailer/templates/mailer_spec.rb000066400000000000000000000014251320451746500260720ustar00rootroot00000000000000require "rails_helper" <% module_namespacing do -%> RSpec.describe <%= Rails.version.to_f >= 5.0 ? class_name.sub(/(Mailer)?$/, 'Mailer') : class_name %>, <%= type_metatag(:mailer) %> do <% for action in actions -%> describe "<%= action %>" do let(:mail) { <%= Rails.version.to_f >= 5.0 ? class_name.sub(/(Mailer)?$/, 'Mailer') : class_name %>.<%= action %> } it "renders the headers" do expect(mail.subject).to eq(<%= action.to_s.humanize.inspect %>) expect(mail.to).to eq(["to@example.org"]) expect(mail.from).to eq(["from@example.com"]) end it "renders the body" do expect(mail.body.encoded).to match("Hi") end end <% end -%> <% if actions.blank? -%> pending "add some examples to (or delete) #{__FILE__}" <% end -%> end <% end -%> rspec-rails-3.7.2/lib/generators/rspec/mailer/templates/preview.rb000066400000000000000000000006501320451746500252670ustar00rootroot00000000000000<% module_namespacing do -%> # Preview all emails at http://localhost:3000/rails/mailers/<%= file_path %> class <%= class_name %>Preview < ActionMailer::Preview <% actions.each do |action| -%> # Preview this email at http://localhost:3000/rails/mailers/<%= file_path %>/<%= action %> def <%= action %> <%= class_name %><%= Rails.version.to_f >= 5.0 ? "Mailer" : "" %>.<%= action %> end <% end -%> end <% end -%> rspec-rails-3.7.2/lib/generators/rspec/model/000077500000000000000000000000001320451746500211115ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/model/model_generator.rb000066400000000000000000000015371320451746500246120ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators # @private class ModelGenerator < Base argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" class_option :fixture, :type => :boolean def create_model_spec template_file = File.join( 'spec/models', class_path, "#{file_name}_spec.rb" ) template 'model_spec.rb', template_file end hook_for :fixture_replacement def create_fixture_file return unless missing_fixture_replacement? template 'fixtures.yml', File.join('spec/fixtures', "#{table_name}.yml") end private def missing_fixture_replacement? options[:fixture] && options[:fixture_replacement].nil? end end end end rspec-rails-3.7.2/lib/generators/rspec/model/templates/000077500000000000000000000000001320451746500231075ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/model/templates/fixtures.yml000066400000000000000000000006201320451746500255010ustar00rootroot00000000000000# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.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-3.7.2/lib/generators/rspec/model/templates/model_spec.rb000066400000000000000000000002761320451746500255530ustar00rootroot00000000000000require 'rails_helper' <% module_namespacing do -%> RSpec.describe <%= class_name %>, <%= type_metatag(:model) %> do pending "add some examples to (or delete) #{__FILE__}" end <% end -%> rspec-rails-3.7.2/lib/generators/rspec/observer/000077500000000000000000000000001320451746500216405ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/observer/observer_generator.rb000066400000000000000000000004531320451746500260640ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators # @private 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-3.7.2/lib/generators/rspec/observer/templates/000077500000000000000000000000001320451746500236365ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/observer/templates/observer_spec.rb000066400000000000000000000003111320451746500270170ustar00rootroot00000000000000require 'rails_helper' <% module_namespacing do -%> RSpec.describe <%= class_name %>Observer, <%= type_metatag(:observer) %> do pending "add some examples to (or delete) #{__FILE__}" end <% end -%> rspec-rails-3.7.2/lib/generators/rspec/request/000077500000000000000000000000001320451746500215015ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/request/request_generator.rb000066400000000000000000000004021320451746500255600ustar00rootroot00000000000000require 'generators/rspec/integration/integration_generator' module Rspec module Generators # @private class RequestGenerator < IntegrationGenerator source_paths << File.expand_path("../../integration/templates", __FILE__) end end end rspec-rails-3.7.2/lib/generators/rspec/scaffold/000077500000000000000000000000001320451746500215725ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/scaffold/scaffold_generator.rb000066400000000000000000000070751320451746500257570ustar00rootroot00000000000000require 'generators/rspec' require 'rails/generators/resource_helpers' module Rspec module Generators # @private 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 :api, :type => :boolean, :desc => "Skip specs unnecessary for API-only apps" 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 :helper_specs, :type => :boolean, :default => true, :desc => "Generate helper specs" class_option :routing_specs, :type => :boolean, :default => true, :desc => "Generate routing specs" def initialize(*args, &blk) @generator_args = args.first super(*args, &blk) end def generate_controller_spec return unless options[:controller_specs] template_file = File.join( 'spec/controllers', controller_class_path, "#{controller_file_name}_controller_spec.rb" ) if options[:api] template 'api_controller_spec.rb', template_file else template 'controller_spec.rb', template_file end end def generate_view_specs return if options[:api] 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_file = File.join( 'spec/routing', controller_class_path, "#{controller_file_name}_routing_spec.rb" ) template 'routing_spec.rb', template_file end hook_for :integration_tool, :as => :integration protected attr_reader :generator_args def copy_view(view) template "#{view}_spec.rb", File.join("spec/views", controller_file_path, "#{view}.html.#{options[:template_engine]}_spec.rb") 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 = generator_args[0].to_s.match(/\A(\w+)(?:\/|::)(\w+)/) matches ? [matches[1], matches[2]] : [] end end def value_for(attribute) raw_value_for(attribute).inspect end def raw_value_for(attribute) case attribute.type when :string attribute.name.titleize when :integer, :float @attribute_id_map ||= {} @attribute_id_map[attribute] ||= @attribute_id_map.keys.size.next + attribute.default else attribute.default end end def banner self.class.banner end end end end rspec-rails-3.7.2/lib/generators/rspec/scaffold/templates/000077500000000000000000000000001320451746500235705ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/scaffold/templates/api_controller_spec.rb000066400000000000000000000147571320451746500301610ustar00rootroot00000000000000require 'rails_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. # # Also compared to earlier versions of this generator, there are no longer any # expectations of assigns and templates rendered. These features have been # removed from Rails core in Rails 5, but can be added back in via the # `rails-controller-testing` gem. <% module_namespacing do -%> RSpec.describe <%= controller_class_name %>Controller, <%= type_metatag(: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) { skip("Add a hash of attributes valid for your model") } let(:invalid_attributes) { skip("Add a hash of attributes invalid for your model") } # 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 "returns a success response" do <%= file_name %> = <%= class_name %>.create! valid_attributes <% if RUBY_VERSION < '1.9.3' -%> get :index, {}, valid_session <% else -%> get :index, params: {}, session: valid_session <% end -%> expect(response).to be_success end end <% end -%> describe "GET #show" do it "returns a success response" do <%= file_name %> = <%= class_name %>.create! valid_attributes <% if RUBY_VERSION < '1.9.3' -%> get :show, {:id => <%= file_name %>.to_param}, valid_session <% else -%> get :show, params: {id: <%= file_name %>.to_param}, session: valid_session <% end -%> expect(response).to be_success end end describe "POST #create" do context "with valid params" do it "creates a new <%= class_name %>" do expect { <% if RUBY_VERSION < '1.9.3' -%> post :create, {:<%= ns_file_name %> => valid_attributes}, valid_session <% else -%> post :create, params: {<%= ns_file_name %>: valid_attributes}, session: valid_session <% end -%> }.to change(<%= class_name %>, :count).by(1) end it "renders a JSON response with the new <%= ns_file_name %>" do <% if RUBY_VERSION < '1.9.3' -%> post :create, {:<%= ns_file_name %> => valid_attributes}, valid_session <% else %> post :create, params: {<%= ns_file_name %>: valid_attributes}, session: valid_session <% end -%> expect(response).to have_http_status(:created) expect(response.content_type).to eq('application/json') expect(response.location).to eq(<%= ns_file_name %>_url(<%= class_name %>.last)) end end context "with invalid params" do it "renders a JSON response with errors for the new <%= ns_file_name %>" do <% if RUBY_VERSION < '1.9.3' -%> post :create, {:<%= ns_file_name %> => invalid_attributes}, valid_session <% else %> post :create, params: {<%= ns_file_name %>: invalid_attributes}, session: valid_session <% end -%> expect(response).to have_http_status(:unprocessable_entity) expect(response.content_type).to eq('application/json') end end end describe "PUT #update" do context "with valid params" do let(:new_attributes) { skip("Add a hash of attributes valid for your model") } it "updates the requested <%= ns_file_name %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes <% if RUBY_VERSION < '1.9.3' -%> put :update, {:id => <%= file_name %>.to_param, :<%= ns_file_name %> => new_attributes}, valid_session <% else -%> put :update, params: {id: <%= file_name %>.to_param, <%= ns_file_name %>: new_attributes}, session: valid_session <% end -%> <%= file_name %>.reload skip("Add assertions for updated state") end it "renders a JSON response with the <%= ns_file_name %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes <% if RUBY_VERSION < '1.9.3' -%> put :update, {:id => <%= file_name %>.to_param, :<%= ns_file_name %> => valid_attributes}, valid_session <% else %> put :update, params: {id: <%= file_name %>.to_param, <%= ns_file_name %>: valid_attributes}, session: valid_session <% end -%> expect(response).to have_http_status(:ok) expect(response.content_type).to eq('application/json') end end context "with invalid params" do it "renders a JSON response with errors for the <%= ns_file_name %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes <% if RUBY_VERSION < '1.9.3' -%> put :update, {:id => <%= file_name %>.to_param, :<%= ns_file_name %> => invalid_attributes}, valid_session <% else %> put :update, params: {id: <%= file_name %>.to_param, <%= ns_file_name %>: invalid_attributes}, session: valid_session <% end -%> expect(response).to have_http_status(:unprocessable_entity) expect(response.content_type).to eq('application/json') end end end describe "DELETE #destroy" do it "destroys the requested <%= ns_file_name %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes expect { <% if RUBY_VERSION < '1.9.3' -%> delete :destroy, {:id => <%= file_name %>.to_param}, valid_session <% else -%> delete :destroy, params: {id: <%= file_name %>.to_param}, session: valid_session <% end -%> }.to change(<%= class_name %>, :count).by(-1) end end end <% end -%> rspec-rails-3.7.2/lib/generators/rspec/scaffold/templates/controller_spec.rb000066400000000000000000000163201320451746500273140ustar00rootroot00000000000000require 'rails_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. # # Also compared to earlier versions of this generator, there are no longer any # expectations of assigns and templates rendered. These features have been # removed from Rails core in Rails 5, but can be added back in via the # `rails-controller-testing` gem. <% module_namespacing do -%> RSpec.describe <%= controller_class_name %>Controller, <%= type_metatag(: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) { skip("Add a hash of attributes valid for your model") } let(:invalid_attributes) { skip("Add a hash of attributes invalid for your model") } # 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 "returns a success response" do <%= file_name %> = <%= class_name %>.create! valid_attributes <% if Rails::VERSION::STRING < '5.0' -%> get :index, {}, valid_session <% else -%> get :index, params: {}, session: valid_session <% end -%> expect(response).to be_success end end <% end -%> describe "GET #show" do it "returns a success response" do <%= file_name %> = <%= class_name %>.create! valid_attributes <% if Rails::VERSION::STRING < '5.0' -%> get :show, {:id => <%= file_name %>.to_param}, valid_session <% else -%> get :show, params: {id: <%= file_name %>.to_param}, session: valid_session <% end -%> expect(response).to be_success end end describe "GET #new" do it "returns a success response" do <% if Rails::VERSION::STRING < '5.0' -%> get :new, {}, valid_session <% else -%> get :new, params: {}, session: valid_session <% end -%> expect(response).to be_success end end describe "GET #edit" do it "returns a success response" do <%= file_name %> = <%= class_name %>.create! valid_attributes <% if Rails::VERSION::STRING < '5.0' -%> get :edit, {:id => <%= file_name %>.to_param}, valid_session <% else -%> get :edit, params: {id: <%= file_name %>.to_param}, session: valid_session <% end -%> expect(response).to be_success end end describe "POST #create" do context "with valid params" do it "creates a new <%= class_name %>" do expect { <% if Rails::VERSION::STRING < '5.0' -%> post :create, {:<%= ns_file_name %> => valid_attributes}, valid_session <% else -%> post :create, params: {<%= ns_file_name %>: valid_attributes}, session: valid_session <% end -%> }.to change(<%= class_name %>, :count).by(1) end it "redirects to the created <%= ns_file_name %>" do <% if Rails::VERSION::STRING < '5.0' -%> post :create, {:<%= ns_file_name %> => valid_attributes}, valid_session <% else -%> post :create, params: {<%= ns_file_name %>: valid_attributes}, session: valid_session <% end -%> expect(response).to redirect_to(<%= class_name %>.last) end end context "with invalid params" do it "returns a success response (i.e. to display the 'new' template)" do <% if Rails::VERSION::STRING < '5.0' -%> post :create, {:<%= ns_file_name %> => invalid_attributes}, valid_session <% else -%> post :create, params: {<%= ns_file_name %>: invalid_attributes}, session: valid_session <% end -%> expect(response).to be_success end end end describe "PUT #update" do context "with valid params" do let(:new_attributes) { skip("Add a hash of attributes valid for your model") } it "updates the requested <%= ns_file_name %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes <% if Rails::VERSION::STRING < '5.0' -%> put :update, {:id => <%= file_name %>.to_param, :<%= ns_file_name %> => new_attributes}, valid_session <% else -%> put :update, params: {id: <%= file_name %>.to_param, <%= ns_file_name %>: new_attributes}, session: valid_session <% end -%> <%= file_name %>.reload skip("Add assertions for updated state") end it "redirects to the <%= ns_file_name %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes <% if Rails::VERSION::STRING < '5.0' -%> put :update, {:id => <%= file_name %>.to_param, :<%= ns_file_name %> => valid_attributes}, valid_session <% else -%> put :update, params: {id: <%= file_name %>.to_param, <%= ns_file_name %>: valid_attributes}, session: valid_session <% end -%> expect(response).to redirect_to(<%= file_name %>) end end context "with invalid params" do it "returns a success response (i.e. to display the 'edit' template)" do <%= file_name %> = <%= class_name %>.create! valid_attributes <% if Rails::VERSION::STRING < '5.0' -%> put :update, {:id => <%= file_name %>.to_param, :<%= ns_file_name %> => invalid_attributes}, valid_session <% else -%> put :update, params: {id: <%= file_name %>.to_param, <%= ns_file_name %>: invalid_attributes}, session: valid_session <% end -%> expect(response).to be_success end end end describe "DELETE #destroy" do it "destroys the requested <%= ns_file_name %>" do <%= file_name %> = <%= class_name %>.create! valid_attributes expect { <% if Rails::VERSION::STRING < '5.0' -%> delete :destroy, {:id => <%= file_name %>.to_param}, valid_session <% else -%> delete :destroy, params: {id: <%= file_name %>.to_param}, session: valid_session <% end -%> }.to change(<%= class_name %>, :count).by(-1) end it "redirects to the <%= table_name %> list" do <%= file_name %> = <%= class_name %>.create! valid_attributes <% if Rails::VERSION::STRING < '5.0' -%> delete :destroy, {:id => <%= file_name %>.to_param}, valid_session <% else -%> delete :destroy, params: {id: <%= file_name %>.to_param}, session: valid_session <% end -%> expect(response).to redirect_to(<%= index_helper %>_url) end end end <% end -%> rspec-rails-3.7.2/lib/generators/rspec/scaffold/templates/edit_spec.rb000066400000000000000000000023361320451746500260600ustar00rootroot00000000000000require 'rails_helper' <% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%> RSpec.describe "<%= ns_table_name %>/edit", <%= type_metatag(:view) %> do before(:each) do @<%= ns_file_name %> = assign(:<%= ns_file_name %>, <%= class_name %>.create!(<%= '))' if 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 assert_select "form[action=?][method=?]", <%= ns_file_name %>_path(@<%= ns_file_name %>), "post" do <% for attribute in output_attributes -%> <%- name = attribute.respond_to?(:column_name) ? attribute.column_name : attribute.name %> <% if Rails.version.to_f >= 5.1 -%> assert_select "<%= attribute.input_type -%>[name=?]", "<%= ns_file_name %>[<%= name %>]" <% else -%> assert_select "<%= attribute.input_type -%>#<%= ns_file_name %>_<%= name %>[name=?]", "<%= ns_file_name %>[<%= name %>]" <% end -%> <% end -%> end end end rspec-rails-3.7.2/lib/generators/rspec/scaffold/templates/index_spec.rb000066400000000000000000000016711320451746500262430ustar00rootroot00000000000000require 'rails_helper' <% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%> RSpec.describe "<%= ns_table_name %>/index", <%= type_metatag(:view) %> do before(:each) do assign(:<%= table_name %>, [ <% [1,2].each_with_index do |id, model_index| -%> <%= class_name %>.create!(<%= 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 <% for attribute in output_attributes -%> assert_select "tr>td", :text => <%= value_for(attribute) %>.to_s, :count => 2 <% end -%> end end rspec-rails-3.7.2/lib/generators/rspec/scaffold/templates/new_spec.rb000066400000000000000000000022531320451746500257220ustar00rootroot00000000000000require 'rails_helper' <% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%> RSpec.describe "<%= ns_table_name %>/new", <%= type_metatag(:view) %> do before(:each) do assign(:<%= ns_file_name %>, <%= class_name %>.new(<%= '))' if 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" : " end" %> it "renders new <%= ns_file_name %> form" do render assert_select "form[action=?][method=?]", <%= index_helper %>_path, "post" do <% for attribute in output_attributes -%> <%- name = attribute.respond_to?(:column_name) ? attribute.column_name : attribute.name %> <% if Rails.version.to_f >= 5.1 -%> assert_select "<%= attribute.input_type -%>[name=?]", "<%= ns_file_name %>[<%= name %>]" <% else -%> assert_select "<%= attribute.input_type -%>#<%= ns_file_name %>_<%= name %>[name=?]", "<%= ns_file_name %>[<%= name %>]" <% end -%> <% end -%> end end end rspec-rails-3.7.2/lib/generators/rspec/scaffold/templates/routing_spec.rb000066400000000000000000000027011320451746500266160ustar00rootroot00000000000000require "rails_helper" <% module_namespacing do -%> RSpec.describe <%= controller_class_name %>Controller, <%= type_metatag(:routing) %> do describe "routing" do <% unless options[:singleton] -%> it "routes to #index" do expect(:get => "/<%= ns_table_name %>").to route_to("<%= ns_table_name %>#index") end <% end -%> <% unless options[:api] -%> it "routes to #new" do expect(:get => "/<%= ns_table_name %>/new").to route_to("<%= ns_table_name %>#new") end <% end -%> it "routes to #show" do expect(:get => "/<%= ns_table_name %>/1").to route_to("<%= ns_table_name %>#show", :id => "1") end <% unless options[:api] -%> it "routes to #edit" do expect(:get => "/<%= ns_table_name %>/1/edit").to route_to("<%= ns_table_name %>#edit", :id => "1") end <% end -%> it "routes to #create" do expect(:post => "/<%= ns_table_name %>").to route_to("<%= ns_table_name %>#create") end it "routes to #update via PUT" do expect(:put => "/<%= ns_table_name %>/1").to route_to("<%= ns_table_name %>#update", :id => "1") end <% if Rails::VERSION::STRING > '4' -%> it "routes to #update via PATCH" do expect(:patch => "/<%= ns_table_name %>/1").to route_to("<%= ns_table_name %>#update", :id => "1") end <% end -%> it "routes to #destroy" do expect(:delete => "/<%= ns_table_name %>/1").to route_to("<%= ns_table_name %>#destroy", :id => "1") end end end <% end -%> rspec-rails-3.7.2/lib/generators/rspec/scaffold/templates/show_spec.rb000066400000000000000000000014421320451746500261100ustar00rootroot00000000000000require 'rails_helper' <% output_attributes = attributes.reject{|attribute| [:datetime, :timestamp, :time, :date].index(attribute.type) } -%> RSpec.describe "<%= ns_table_name %>/show", <%= type_metatag(:view) %> do before(:each) do @<%= ns_file_name %> = assign(:<%= ns_file_name %>, <%= class_name %>.create!(<%= '))' if 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 <% for attribute in output_attributes -%> expect(rendered).to match(/<%= raw_value_for(attribute) %>/) <% end -%> end end rspec-rails-3.7.2/lib/generators/rspec/view/000077500000000000000000000000001320451746500207635ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/view/templates/000077500000000000000000000000001320451746500227615ustar00rootroot00000000000000rspec-rails-3.7.2/lib/generators/rspec/view/templates/view_spec.rb000066400000000000000000000002451320451746500252730ustar00rootroot00000000000000require 'rails_helper' RSpec.describe "<%= file_path %>/<%= @action %>", <%= type_metatag(:view) %> do pending "add some examples to (or delete) #{__FILE__}" end rspec-rails-3.7.2/lib/generators/rspec/view/view_generator.rb000066400000000000000000000011541320451746500243310ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators # @private 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-3.7.2/lib/rspec-rails.rb000066400000000000000000000055221320451746500173010ustar00rootroot00000000000000require 'rspec/rails/feature_check' # Namespace for all core RSpec projects. module RSpec # Namespace for rspec-rails code. module Rails # Railtie to hook into Rails. class Railtie < ::Rails::Railtie # As of Rails 5.1.0 you can register directories to work with `rake notes` if ::Rails::VERSION::STRING >= '5.1' require 'rails/source_annotation_extractor' SourceAnnotationExtractor::Annotation.register_directories("spec") end # 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 generators do ::Rails::Generators.hidden_namespaces.reject! { |namespace| namespace.to_s.start_with?("rspec") } end rake_tasks do load "rspec/rails/tasks/rspec.rake" end # This is called after the environment has been loaded but before Rails # sets the default for the `preview_path` initializer "rspec_rails.action_mailer", :before => "action_mailer.set_configs" do |app| setup_preview_path(app) end private def setup_preview_path(app) return unless supports_action_mailer_previews?(app.config) options = app.config.action_mailer config_default_preview_path(options) if config_preview_path?(options) end def config_preview_path?(options) # We cannot use `respond_to?(:show_previews)` here as it will always # return `true`. if ::Rails::VERSION::STRING < '4.2' ::Rails.env.development? elsif options.show_previews.nil? options.show_previews = ::Rails.env.development? else options.show_previews end end def config_default_preview_path(options) return unless options.preview_path.blank? options.preview_path = "#{::Rails.root}/spec/mailers/previews" end def supports_action_mailer_previews?(config) # These checks avoid loading `ActionMailer`. Using `defined?` has the # side-effect of the class getting loaded if it is available. This is # problematic because loading `ActionMailer::Base` will cause it to # read the config settings; this is the only time the config is read. # If the config is loaded now, any settings declared in a config block # in an initializer will be ignored. # # If the action mailer railtie has not been loaded then `config` will # not respond to the method. However, we cannot use # `config.action_mailer.respond_to?(:preview_path)` here as it will # always return `true`. config.respond_to?(:action_mailer) && ::Rails::VERSION::STRING > '4.1' end end end end rspec-rails-3.7.2/lib/rspec/000077500000000000000000000000001320451746500156405ustar00rootroot00000000000000rspec-rails-3.7.2/lib/rspec/rails.rb000066400000000000000000000011021320451746500172710ustar00rootroot00000000000000require 'rspec/core' require 'rails/version' # Load any of our adapters and extensions early in the process require 'rspec/rails/adapters' require 'rspec/rails/extensions' # Load the rspec-rails parts require 'rspec/rails/view_rendering' require 'rspec/rails/matchers' require 'rspec/rails/fixture_support' require 'rspec/rails/file_fixture_support' require 'rspec/rails/fixture_file_upload_support' require 'rspec/rails/example' require 'rspec/rails/vendor/capybara' require 'rspec/rails/configuration' require 'rspec/rails/active_record' require 'rspec/rails/feature_check' rspec-rails-3.7.2/lib/rspec/rails/000077500000000000000000000000001320451746500167525ustar00rootroot00000000000000rspec-rails-3.7.2/lib/rspec/rails/active_record.rb000066400000000000000000000017731320451746500221200ustar00rootroot00000000000000module RSpec module Rails # Fake class to document RSpec ActiveRecord configuration options. In practice, # these are dynamically added to the normal RSpec configuration object. class ActiveRecordConfiguration # @private def self.initialize_activerecord_configuration(config) config.before :suite do # This allows dynamic columns etc to be used on ActiveRecord models when creating instance_doubles if defined?(ActiveRecord) && defined?(ActiveRecord::Base) && defined?(::RSpec::Mocks) && (::RSpec::Mocks.respond_to?(:configuration)) ::RSpec::Mocks.configuration.when_declaring_verifying_double do |possible_model| target = possible_model.target if Class === target && ActiveRecord::Base > target && !target.abstract_class? target.define_attribute_methods end end end end end initialize_activerecord_configuration RSpec.configuration end end end rspec-rails-3.7.2/lib/rspec/rails/adapters.rb000066400000000000000000000167401320451746500211120ustar00rootroot00000000000000require 'delegate' require 'active_support' require 'active_support/concern' require 'active_support/core_ext/string' module RSpec module Rails # @private def self.disable_testunit_autorun # `Test::Unit::AutoRunner.need_auto_run=` was introduced to the test-unit # gem in version 2.4.9. Previous to this version `Test::Unit.run=` was # used. The implementation of test-unit included with Ruby has neither # method. if defined?(Test::Unit::AutoRunner.need_auto_run = ()) Test::Unit::AutoRunner.need_auto_run = false elsif defined?(Test::Unit.run = ()) Test::Unit.run = false end end private_class_method :disable_testunit_autorun if ::Rails::VERSION::STRING >= '4.1.0' if defined?(Kernel.gem) gem 'minitest' else require 'minitest' end require 'minitest/assertions' # Constant aliased to either Minitest or TestUnit, depending on what is # loaded. Assertions = Minitest::Assertions elsif RUBY_VERSION >= '2.2.0' # Minitest / TestUnit has been removed from ruby core. However, we are # on an old Rails version and must load the appropriate gem if ::Rails::VERSION::STRING >= '4.0.0' # ActiveSupport 4.0.x has the minitest '~> 4.2' gem as a dependency # This gem has no `lib/minitest.rb` file. gem 'minitest' if defined?(Kernel.gem) require 'minitest/unit' Assertions = MiniTest::Assertions elsif ::Rails::VERSION::STRING >= '3.2.21' # TODO: Change the above check to >= '3.2.22' once it's released begin # Test::Unit "helpfully" sets up autoload for its `AutoRunner`. # While we do not reference it directly, when we load the `TestCase` # classes from AS (ActiveSupport), AS kindly references `AutoRunner` # for everyone. # # To handle this we need to pre-emptively load 'test/unit' and make # sure the version installed has `AutoRunner` (the 3.x line does to # date). If so, we turn the auto runner off. require 'test/unit' require 'test/unit/assertions' disable_testunit_autorun rescue LoadError => e raise LoadError, <<-ERR.squish, e.backtrace Ruby 2.2+ has removed test/unit from the core library. Rails requires this as a dependency. Please add test-unit gem to your Gemfile: `gem 'test-unit', '~> 3.0'` (#{e.message})" ERR end Assertions = Test::Unit::Assertions else abort <<-MSG.squish Ruby 2.2+ is not supported on Rails #{::Rails::VERSION::STRING}. Check the Rails release notes for the appropriate update with support. MSG end else begin require 'test/unit/assertions' rescue LoadError # work around for Rubinius not having a std std-lib require 'rubysl-test-unit' if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx' require 'test/unit/assertions' end # Turn off test unit's auto runner for those using the gem disable_testunit_autorun # Constant aliased to either Minitest or TestUnit, depending on what is # loaded. Assertions = Test::Unit::Assertions end # @private class AssertionDelegator < Module def initialize(*assertion_modules) assertion_class = Class.new(SimpleDelegator) do include ::RSpec::Rails::Assertions include ::RSpec::Rails::MinitestCounters assertion_modules.each { |mod| include mod } end super() do define_method :build_assertion_instance do assertion_class.new(self) end 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" define_method(method.to_sym) do |*args, &block| assertion_instance.send(method.to_sym, *args, &block) end end end end end end # Adapts example groups for `Minitest::Test::LifecycleHooks` # # @private 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 # @private module MinitestCounters attr_writer :assertions def assertions @assertions ||= 0 end end # @private module SetupAndTeardownAdapter extend ActiveSupport::Concern module ClassMethods # Wraps `setup` calls from within Rails' testing framework in `before` # hooks. def setup(*methods, &block) methods.each do |method| if method.to_s =~ /^setup_(with_controller|fixtures|controller_request_and_response)$/ prepend_before { __send__ method } else before { __send__ method } end end before(&block) if block end # @api private # # Wraps `teardown` calls from within Rails' testing framework in # `after` hooks. def teardown(*methods, &block) methods.each { |method| after { __send__ method } } after(&block) if block end end def initialize(*args) super @example = nil end def method_name @example end end # @private module MinitestAssertionAdapter extend ActiveSupport::Concern # @private module ClassMethods # 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 methods = ::RSpec::Rails::Assertions. public_instance_methods. select do |m| m.to_s =~ /^(assert|flunk|refute)/ end methods + test_unit_specific_methods end def define_assertion_delegators assertion_method_names.each do |m| define_method(m.to_sym) do |*args, &block| assertion_delegator.send(m.to_sym, *args, &block) end end end # Starting on Rails 4, Minitest is the default testing framework so no # need to add TestUnit specific methods. if ::Rails::VERSION::STRING >= '4.0.0' def test_unit_specific_methods [] end else def test_unit_specific_methods [:build_message] end end end class AssertionDelegator include ::RSpec::Rails::Assertions include ::RSpec::Rails::MinitestCounters end def assertion_delegator @assertion_delegator ||= AssertionDelegator.new end included do define_assertion_delegators end end # Backwards compatibility. It's unlikely that anyone is using this # constant, but we had forgotten to mark it as `@private` earlier # # @private TestUnitAssertionAdapter = MinitestAssertionAdapter end end rspec-rails-3.7.2/lib/rspec/rails/configuration.rb000066400000000000000000000132001320451746500221420ustar00rootroot00000000000000module RSpec module Rails # Fake class to document RSpec Rails configuration options. In practice, # these are dynamically added to the normal RSpec configuration object. class Configuration # @!method infer_spec_type_from_file_location! # Automatically tag specs in conventional directories with matching `type` # metadata so that they have relevant helpers available to them. See # `RSpec::Rails::DIRECTORY_MAPPINGS` for details on which metadata is # applied to each directory. # @!method render_views=(val) # # When set to `true`, controller specs will render the relevant view as # well. Defaults to `false`. # @!method render_views(val) # Enables view rendering for controllers specs. # @!method render_views? # Reader for currently value of `render_views` setting. end # Mappings used by `infer_spec_type_from_file_location!`. # # @api private DIRECTORY_MAPPINGS = { :controller => %w[spec controllers], :helper => %w[spec helpers], :job => %w[spec jobs], :mailer => %w[spec mailers], :model => %w[spec models], :request => %w[spec (requests|integration|api)], :routing => %w[spec routing], :view => %w[spec views], :feature => %w[spec features], :system => %w[spec system] } # Sets up the different example group modules for the different spec types # # @api private def self.add_test_type_configurations(config) config.include RSpec::Rails::ControllerExampleGroup, :type => :controller config.include RSpec::Rails::HelperExampleGroup, :type => :helper config.include RSpec::Rails::ModelExampleGroup, :type => :model config.include RSpec::Rails::RequestExampleGroup, :type => :request config.include RSpec::Rails::RoutingExampleGroup, :type => :routing config.include RSpec::Rails::ViewExampleGroup, :type => :view config.include RSpec::Rails::FeatureExampleGroup, :type => :feature config.include RSpec::Rails::Matchers config.include RSpec::Rails::SystemExampleGroup, :type => :system end # @private # rubocop:disable Style/MethodLength def self.initialize_configuration(config) config.backtrace_exclusion_patterns << /vendor\// config.backtrace_exclusion_patterns << %r{lib/rspec/rails} # controller settings config.add_setting :infer_base_class_for_anonymous_controllers, :default => true # fixture support config.add_setting :use_transactional_fixtures, :alias_with => :use_transactional_examples config.add_setting :use_instantiated_fixtures config.add_setting :global_fixtures config.add_setting :fixture_path config.include RSpec::Rails::FixtureSupport, :use_fixtures # We'll need to create a deprecated module in order to properly report to # gems / projects which are relying on this being loaded globally. # # See rspec/rspec-rails#1355 for history # # @deprecated Include `RSpec::Rails::RailsExampleGroup` or # `RSpec::Rails::FixtureSupport` directly instead config.include RSpec::Rails::FixtureSupport if ::Rails::VERSION::STRING > '5' config.add_setting :file_fixture_path, :default => 'spec/fixtures/files' config.include RSpec::Rails::FileFixtureSupport end # Add support for fixture_path on fixture_file_upload config.include RSpec::Rails::FixtureFileUploadSupport # 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 config.instance_exec do def render_views=(val) self.rendering_views = val end def render_views self.rendering_views = true end def render_views? rendering_views end def infer_spec_type_from_file_location! DIRECTORY_MAPPINGS.each do |type, dir_parts| escaped_path = Regexp.compile(dir_parts.join('[\\\/]') + '[\\\/]') define_derived_metadata(:file_path => escaped_path) do |metadata| metadata[:type] ||= type end end end # Adds exclusion filters for gems included with Rails def filter_rails_from_backtrace! filter_gems_from_backtrace "actionmailer", "actionpack", "actionview" filter_gems_from_backtrace "activemodel", "activerecord", "activesupport", "activejob" end end add_test_type_configurations(config) if defined?(::Rails::Controller::Testing) [:controller, :view, :request].each do |type| config.include ::Rails::Controller::Testing::TestProcess, :type => type config.include ::Rails::Controller::Testing::TemplateAssertions, :type => type config.include ::Rails::Controller::Testing::Integration, :type => type end end if defined?(ActionMailer) config.include RSpec::Rails::MailerExampleGroup, :type => :mailer end if defined?(ActiveJob) config.include RSpec::Rails::JobExampleGroup, :type => :job end end # rubocop:enable Style/MethodLength initialize_configuration RSpec.configuration end end rspec-rails-3.7.2/lib/rspec/rails/example.rb000066400000000000000000000010611320451746500207300ustar00rootroot00000000000000require '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/job_example_group' require 'rspec/rails/example/feature_example_group' require 'rspec/rails/example/system_example_group' rspec-rails-3.7.2/lib/rspec/rails/example/000077500000000000000000000000001320451746500204055ustar00rootroot00000000000000rspec-rails-3.7.2/lib/rspec/rails/example/controller_example_group.rb000066400000000000000000000163111320451746500260460ustar00rootroot00000000000000module RSpec module Rails # @private ControllerAssertionDelegator = RSpec::Rails::AssertionDelegator.new( ActionDispatch::Assertions::RoutingAssertions ) # @api public # Container module for controller spec functionality. 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 ControllerAssertionDelegator # Class-level DSL for controller specs. 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 anonymous 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) if RSpec.configuration.infer_base_class_for_anonymous_controllers? base_class ||= controller_class end base_class ||= defined?(ApplicationController) ? ApplicationController : ActionController::Base new_controller_class = Class.new(base_class) do def self.name root_controller = defined?(ApplicationController) ? ApplicationController : ActionController::Base if superclass == root_controller || superclass.abstract? "AnonymousController" else superclass.name end end end new_controller_class.class_exec(&body) (class << self; self; end).__send__(:define_method, :controller_class) { new_controller_class } before do @orig_routes = routes resource_name = if @controller.respond_to?(:controller_name) @controller.controller_name.to_sym else :anonymous end resource_path = if @controller.respond_to?(:controller_path) @controller.controller_path else resource_name.to_s end resource_module = resource_path.rpartition('/').first.presence resource_as = 'anonymous_' + resource_path.tr('/', '_') self.routes = ActionDispatch::Routing::RouteSet.new.tap do |r| r.draw do resources resource_name, :as => resource_as, :module => resource_module, :path => resource_path end end 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 before do self.routes = yield end end end # @!attribute [r] # Returns the controller object instance under test. attr_reader :controller # @!attribute [r] # Returns the Rails routes used for the spec. attr_reader :routes # @private # # RSpec Rails uses this to make Rails routes easily available to specs. def routes=(routes) @routes = routes assertion_instance.instance_variable_set(:@routes, routes) end # @private 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 route_available?(method) controller.send(method, *args, &block) else super end end included do subject { 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 private def route_available?(method) (defined?(@routes) && route_defined?(routes, method)) || (defined?(@orig_routes) && route_defined?(@orig_routes, method)) end def route_defined?(routes, method) return false if routes.nil? if routes.named_routes.respond_to?(:route_defined?) routes.named_routes.route_defined?(method) else routes.named_routes.helpers.include?(method) end end end end end rspec-rails-3.7.2/lib/rspec/rails/example/feature_example_group.rb000066400000000000000000000050731320451746500253210ustar00rootroot00000000000000module RSpec module Rails # @api public # Container module for routing spec functionality. module FeatureExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup # Default host to be used in Rails route helpers if none is specified. DEFAULT_HOST = "www.example.com" included do 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 # Shim to check for presence of Capybara. Will delegate if present, raise # if not. We assume here that in most cases `visit` will be the first # Capybara method called in a spec. def visit(*) if defined?(super) super else raise "Capybara not loaded, please add it to your Gemfile:\n\ngem \"capybara\"" end end end end end unless RSpec.respond_to?(:feature) opts = { :capybara_feature => true, :type => :feature, :skip => <<-EOT.squish Feature specs require the Capybara (http://github.com/jnicklas/capybara) gem, version 2.2.0 or later. We recommend version 2.4.0 or later to avoid some deprecation warnings and have support for `config.expose_dsl_globally = false`. EOT } # Capybara's monkey patching causes us to have to jump through some hoops top_level = self main_feature = nil if defined?(Capybara) && ::Capybara::VERSION.to_f < 2.4 # Capybara 2.2 and 2.3 do not use `alias_example_xyz` opts[:skip] = <<-EOT.squish Capybara < 2.4.0 does not support RSpec's namespace or `config.expose_dsl_globally = false`. Upgrade to Capybara >= 2.4.0. EOT main_feature = top_level.method(:feature) if top_level.respond_to?(:feature) end RSpec.configure do |c| main_feature = nil unless c.expose_dsl_globally? c.alias_example_group_to :feature, opts c.alias_example_to :scenario c.alias_example_to :xscenario, :skip => 'Temporarily skipped with xscenario' end # Due to load order issues and `config.expose_dsl_globally?` defaulting to # `true` we need to put Capybara's monkey patch method back. Otherwise, # app upgrades have a high likelyhood of having all feature specs skipped. top_level.define_singleton_method(:feature, &main_feature) if main_feature end rspec-rails-3.7.2/lib/rspec/rails/example/helper_example_group.rb000066400000000000000000000025031320451746500251400ustar00rootroot00000000000000require 'rspec/rails/view_assigns' module RSpec module Rails # @api public # Container module for helper specs. module HelperExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup include ActionView::TestCase::Behavior include RSpec::Rails::ViewAssigns # @private module ClassMethods if ::Rails::VERSION::MAJOR > 3 def determine_constant_from_test_name(_ignore) described_class if yield(described_class) end else def determine_default_helper_class(_ignore) return unless Module === described_class && !(Class === described_class) described_class end 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.example_group.described_class.to_s.sub(/Helper/, '').underscore end included do before do |example| controller.controller_path = _controller_path(example) end end end end end rspec-rails-3.7.2/lib/rspec/rails/example/job_example_group.rb000066400000000000000000000011321320451746500244300ustar00rootroot00000000000000module RSpec module Rails # @api public # Container module for job spec functionality. It is only available if # ActiveJob has been loaded before it. module JobExampleGroup # This blank module is only necessary for YARD processing. It doesn't # handle the conditional `defined?` check below very well. end end end if defined?(ActiveJob) module RSpec module Rails # Container module for job spec functionality. module JobExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup end end end end rspec-rails-3.7.2/lib/rspec/rails/example/mailer_example_group.rb000066400000000000000000000021321320451746500251300ustar00rootroot00000000000000module RSpec module Rails # @api public # Container module for mailer spec functionality. It is only available if # ActionMailer has been loaded before it. module MailerExampleGroup # This blank module is only necessary for YARD processing. It doesn't # handle the conditional `defined?` check below very well. end end end if defined?(ActionMailer) module RSpec module Rails # Container module for mailer spec functionality. module MailerExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup include ActionMailer::TestCase::Behavior included do 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 # Class-level DSL for mailer specs. module ClassMethods # Alias for `described_class`. def mailer_class described_class end end end end end end rspec-rails-3.7.2/lib/rspec/rails/example/model_example_group.rb000066400000000000000000000004701320451746500247620ustar00rootroot00000000000000module RSpec module Rails # @api public # Container class for model spec functionality. Does not provide anything # special over the common RailsExampleGroup currently. module ModelExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup end end end rspec-rails-3.7.2/lib/rspec/rails/example/rails_example_group.rb000066400000000000000000000010341320451746500247710ustar00rootroot00000000000000# Temporary workaround to resolve circular dependency between rspec-rails' spec # suite and ammeter. require 'rspec/rails/matchers' module RSpec module Rails # @api public # Common rails example functionality. module RailsExampleGroup extend ActiveSupport::Concern include RSpec::Rails::SetupAndTeardownAdapter include RSpec::Rails::MinitestLifecycleAdapter if ::Rails::VERSION::STRING >= '4' include RSpec::Rails::MinitestAssertionAdapter include RSpec::Rails::FixtureSupport end end end rspec-rails-3.7.2/lib/rspec/rails/example/request_example_group.rb000066400000000000000000000014221320451746500253500ustar00rootroot00000000000000module RSpec module Rails # @api public # Container class for request spec functionality. 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 if ActionPack::VERSION::MAJOR >= 5 include ActionDispatch::IntegrationTest::Behavior end # Delegates to `Rails.application`. def app ::Rails.application end included do before do @routes = ::Rails.application.routes end end end end end rspec-rails-3.7.2/lib/rspec/rails/example/routing_example_group.rb000066400000000000000000000033171320451746500253540ustar00rootroot00000000000000require "action_dispatch/testing/assertions/routing" module RSpec module Rails # @private RoutingAssertionDelegator = RSpec::Rails::AssertionDelegator.new( ActionDispatch::Assertions::RoutingAssertions ) # @api public # Container module for routing spec functionality. module RoutingExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup include RSpec::Rails::Matchers::RoutingMatchers include RSpec::Rails::Matchers::RoutingMatchers::RouteHelpers include RSpec::Rails::RoutingAssertionDelegator # Class-level DSL for route specs. 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 before do self.routes = yield end end end included do before do self.routes = ::Rails.application.routes end end # @!attribute [r] # @private attr_reader :routes # @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 end rspec-rails-3.7.2/lib/rspec/rails/example/system_example_group.rb000066400000000000000000000064671320451746500252220ustar00rootroot00000000000000module RSpec module Rails # @api public # Container class for system tests module SystemExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup include RSpec::Rails::Matchers::RedirectTo include RSpec::Rails::Matchers::RenderTemplate include ActionDispatch::Integration::Runner include ActionDispatch::Assertions include ActionController::TemplateAssertions # @private module BlowAwayAfterTeardownHook # @private def after_teardown end end # for the SystemTesting Screenshot situation def passed? return false if RSpec.current_example.exception return true unless defined?(::RSpec::Expectations::FailureAggregator) failure_notifier = ::RSpec::Support.failure_notifier return true unless failure_notifier.is_a?(::RSpec::Expectations::FailureAggregator) failure_notifier.failures.empty? && failure_notifier.other_errors.empty? end # @private def method_name @method_name ||= [ self.class.name.underscore, RSpec.current_example.description.underscore, rand(1000) ].join("_").gsub(/[\/\.:, ]/, "_") end # Delegates to `Rails.application`. def app ::Rails.application end included do |other| begin require 'capybara' require 'action_dispatch/system_test_case' # rubocop:disable Lint/HandleExceptions rescue LoadError # rubocop:enable Lint/HandleExceptions abort """ System test integration requires Rails >= 5.1 and has a hard dependency on a webserver and `capybara`, please add capybara to your Gemfile and configure a webserver (e.g. `Capybara.server = :webrick`) before attempting to use system tests. """.gsub(/\s+/, ' ').strip end original_after_teardown = ::ActionDispatch::SystemTesting::TestHelpers::SetupAndTeardown.instance_method(:after_teardown) other.include ActionDispatch::IntegrationTest::Behavior other.include ::ActionDispatch::SystemTesting::TestHelpers::SetupAndTeardown other.include ::ActionDispatch::SystemTesting::TestHelpers::ScreenshotHelper other.include BlowAwayAfterTeardownHook attr_reader :driver if ActionDispatch::SystemTesting::Server.respond_to?(:silence_puma=) ActionDispatch::SystemTesting::Server.silence_puma = true end def initialize(*args, &blk) super(*args, &blk) @driver = nil end def driven_by(*args, &blk) @driver = ::ActionDispatch::SystemTestCase.driven_by(*args, &blk).tap(&:use) end before do # A user may have already set the driver, so only default if driver # is not set driven_by(:selenium) unless @driver @routes = ::Rails.application.routes end after do orig_stdout = $stdout $stdout = StringIO.new begin original_after_teardown.bind(self).call ensure myio = $stdout RSpec.current_example.metadata[:extra_failure_lines] = myio.string $stdout = orig_stdout end end end end end end rspec-rails-3.7.2/lib/rspec/rails/example/view_example_group.rb000066400000000000000000000143701320451746500246400ustar00rootroot00000000000000require 'rspec/rails/view_assigns' require 'rspec/rails/view_spec_methods' require 'rspec/rails/view_path_builder' module RSpec module Rails # @api public # Container class for view spec functionality. module ViewExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup include ActionView::TestCase::Behavior include RSpec::Rails::ViewAssigns include RSpec::Rails::Matchers::RenderTemplate # @private module ClassMethods def _default_helper base = metadata[:description].split('/')[0..-2].join('/') (base.camelize + 'Helper').constantize unless base.to_s.empty? rescue NameError nil end def _default_helpers helpers = [_default_helper].compact helpers << ApplicationHelper if Object.const_defined?('ApplicationHelper') helpers end end # DSL exposed to view specs. module ExampleMethods extend ActiveSupport::Concern included do include ::Rails.application.routes.url_helpers if ::Rails.application.routes.respond_to?(:mounted_helpers) include ::Rails.application.routes.mounted_helpers end end # @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 && 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. # # 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", :replacement => "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_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.to_sym] 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_exec do include helpers unless included_modules.include?(helpers) end end end included do include ExampleMethods 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 path_params_to_merge = {} path_params_to_merge[:controller] = _controller_path path_params_to_merge[:action] = _inferred_action unless _inferred_action =~ /^_/ path_params = controller.request.path_parameters controller.request.path_parameters = path_params.reverse_merge(path_params_to_merge) controller.request.path = ViewPathBuilder.new(::Rails.application.routes).path_for(controller.request.path_parameters) ViewSpecMethods.add_to(::ActionView::TestCase::TestController) end after do ViewSpecMethods.remove_from(::ActionView::TestCase::TestController) end let(:_default_file_to_render) do |example| example.example_group.top_level_description end end end end end rspec-rails-3.7.2/lib/rspec/rails/extensions.rb000066400000000000000000000000651320451746500214770ustar00rootroot00000000000000require 'rspec/rails/extensions/active_record/proxy' rspec-rails-3.7.2/lib/rspec/rails/extensions/000077500000000000000000000000001320451746500211515ustar00rootroot00000000000000rspec-rails-3.7.2/lib/rspec/rails/extensions/active_record/000077500000000000000000000000001320451746500237625ustar00rootroot00000000000000rspec-rails-3.7.2/lib/rspec/rails/extensions/active_record/proxy.rb000066400000000000000000000012151320451746500254670ustar00rootroot00000000000000RSpec.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-3.7.2/lib/rspec/rails/feature_check.rb000066400000000000000000000030761320451746500220750ustar00rootroot00000000000000module RSpec module Rails # @private # Disable some cops until https://github.com/bbatsov/rubocop/issues/1310 # rubocop:disable Style/IndentationConsistency module FeatureCheck # rubocop:disable Style/IndentationWidth module_function # rubocop:enable Style/IndentationWidth def can_check_pending_migrations? has_active_record_migration? && ::ActiveRecord::Migration.respond_to?(:check_pending!) end def can_maintain_test_schema? has_active_record_migration? && ::ActiveRecord::Migration.respond_to?(:maintain_test_schema!) end def has_active_job? defined?(::ActiveJob) end def has_active_record? defined?(::ActiveRecord) end def has_active_record_migration? has_active_record? && defined?(::ActiveRecord::Migration) end def has_action_mailer? defined?(::ActionMailer) end def has_action_mailer_preview? has_action_mailer? && defined?(::ActionMailer::Preview) end def has_action_mailer_show_preview? has_action_mailer_preview? && ::ActionMailer::Base.respond_to?(:show_previews=) end def has_1_9_hash_syntax? ::Rails::VERSION::STRING > '4.0' end def has_file_fixture? ::Rails::VERSION::STRING > '5.0' end def type_metatag(type) if has_1_9_hash_syntax? "type: :#{type}" else ":type => :#{type}" end end end # rubocop:enable Style/IndentationConsistency end end rspec-rails-3.7.2/lib/rspec/rails/file_fixture_support.rb000066400000000000000000000006061320451746500235620ustar00rootroot00000000000000if ::Rails::VERSION::STRING > '5' require 'active_support/testing/file_fixtures' module RSpec module Rails # @private module FileFixtureSupport extend ActiveSupport::Concern include ActiveSupport::Testing::FileFixtures included do self.file_fixture_path = RSpec.configuration.file_fixture_path end end end end end rspec-rails-3.7.2/lib/rspec/rails/fixture_file_upload_support.rb000066400000000000000000000023051320451746500251240ustar00rootroot00000000000000module RSpec module Rails # @private module FixtureFileUploadSupport delegate :fixture_file_upload, :to => :rails_fixture_file_wrapper private def rails_fixture_file_wrapper resolved_fixture_path = (fixture_path || RSpec.configuration.fixture_path || '') RailsFixtureFileWrapper.fixture_path = File.join(resolved_fixture_path, '') RailsFixtureFileWrapper.instance end class RailsFixtureFileWrapper include ActionDispatch::TestProcess if defined?(ActionDispatch::TestProcess) class << self attr_reader :fixture_path # Get the instance of wrapper def instance @instance ||= new end # Override fixture_path set # to support Rails 3.0->3.1 using ActionController::TestCase class to resolve fixture_path # see https://apidock.com/rails/v3.0.0/ActionDispatch/TestProcess/fixture_file_upload def fixture_path=(value) if ActionController::TestCase.respond_to?(:fixture_path) ActionController::TestCase.fixture_path = value end @fixture_path = value end end end end end end rspec-rails-3.7.2/lib/rspec/rails/fixture_support.rb000066400000000000000000000044521320451746500225660ustar00rootroot00000000000000module RSpec module Rails # @private module FixtureSupport if defined?(ActiveRecord::TestFixtures) extend ActiveSupport::Concern include RSpec::Rails::SetupAndTeardownAdapter include RSpec::Rails::MinitestLifecycleAdapter if ::ActiveRecord::VERSION::STRING > '4' include RSpec::Rails::MinitestAssertionAdapter 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_exec do include ActiveRecord::TestFixtures self.fixture_path = RSpec.configuration.fixture_path end # /TODO self.fixture_path = RSpec.configuration.fixture_path if ::Rails::VERSION::STRING > '5' self.use_transactional_tests = RSpec.configuration.use_transactional_fixtures else self.use_transactional_fixtures = RSpec.configuration.use_transactional_fixtures end self.use_instantiated_fixtures = RSpec.configuration.use_instantiated_fixtures def self.fixtures(*args) orig_methods = private_instance_methods super.tap do new_methods = private_instance_methods - orig_methods new_methods.each do |method_name| proxy_method_warning_if_called_in_before_context_scope(method_name) end end end def self.proxy_method_warning_if_called_in_before_context_scope(method_name) orig_implementation = instance_method(method_name) define_method(method_name) do |*args, &blk| if inspect.include?("before(:context)") RSpec.warn_with("Calling fixture method in before :context ") else orig_implementation.bind(self).call(*args, &blk) end end end fixtures RSpec.configuration.global_fixtures if RSpec.configuration.global_fixtures end end end end end rspec-rails-3.7.2/lib/rspec/rails/matchers.rb000066400000000000000000000012601320451746500211040ustar00rootroot00000000000000require 'rspec/core/warnings' require 'rspec/expectations' require 'rspec/rails/feature_check' module RSpec module Rails # @api public # Container module for Rails specific matchers. module Matchers 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/relation_match_array' require 'rspec/rails/matchers/be_valid' require 'rspec/rails/matchers/have_http_status' if RSpec::Rails::FeatureCheck.has_active_job? require 'rspec/rails/matchers/active_job' end rspec-rails-3.7.2/lib/rspec/rails/matchers/000077500000000000000000000000001320451746500205605ustar00rootroot00000000000000rspec-rails-3.7.2/lib/rspec/rails/matchers/active_job.rb000066400000000000000000000206161320451746500232170ustar00rootroot00000000000000require "active_job/base" require "active_job/arguments" module RSpec module Rails module Matchers # Namespace for various implementations of ActiveJob features # # @api private module ActiveJob # rubocop: disable Style/ClassLength # @private class Base < RSpec::Matchers::BuiltIn::BaseMatcher def initialize @args = [] @queue = nil @at = nil @block = Proc.new {} set_expected_number(:exactly, 1) end def with(*args, &block) @args = args @block = block if block.present? self end def on_queue(queue) @queue = queue self end def at(date) @at = date self end def exactly(count) set_expected_number(:exactly, count) self end def at_least(count) set_expected_number(:at_least, count) self end def at_most(count) set_expected_number(:at_most, count) self end def times self end def once exactly(:once) end def twice exactly(:twice) end def thrice exactly(:thrice) end def failure_message "expected to enqueue #{base_message}".tap do |msg| if @unmatching_jobs.any? msg << "\nQueued jobs:" @unmatching_jobs.each do |job| msg << "\n #{base_job_message(job)}" end end end end def failure_message_when_negated "expected not to enqueue #{base_message}" end def message_expectation_modifier case @expectation_type when :exactly then "exactly" when :at_most then "at most" when :at_least then "at least" end end def supports_block_expectations? true end private def check(jobs) @matching_jobs, @unmatching_jobs = jobs.partition do |job| if arguments_match?(job) && other_attributes_match?(job) args = ::ActiveJob::Arguments.deserialize(job[:args]) @block.call(*args) true else false end end @matching_jobs_count = @matching_jobs.size case @expectation_type when :exactly then @expected_number == @matching_jobs_count when :at_most then @expected_number >= @matching_jobs_count when :at_least then @expected_number <= @matching_jobs_count end end def base_message "#{message_expectation_modifier} #{@expected_number} jobs,".tap do |msg| msg << " with #{@args}," if @args.any? msg << " on queue #{@queue}," if @queue msg << " at #{@at}," if @at msg << " but enqueued #{@matching_jobs_count}" end end def base_job_message(job) msg_parts = [] msg_parts << "with #{::ActiveJob::Arguments.deserialize(job[:args])}" if job[:args].any? msg_parts << "on queue #{job[:queue]}" if job[:queue] msg_parts << "at #{Time.at(job[:at])}" if job[:at] "#{job[:job].name} job".tap do |msg| msg << " #{msg_parts.join(', ')}" if msg_parts.any? end end def arguments_match?(job) if @args.any? deserialized_args = ::ActiveJob::Arguments.deserialize(job[:args]) RSpec::Mocks::ArgumentListMatcher.new(*@args).args_match?(*deserialized_args) else true end end def other_attributes_match?(job) serialized_attributes.all? { |key, value| value == job[key] } end def serialized_attributes {}.tap do |attributes| attributes[:at] = @at.to_f if @at attributes[:queue] = @queue if @queue attributes[:job] = @job if @job end end def set_expected_number(relativity, count) @expectation_type = relativity @expected_number = case count when :once then 1 when :twice then 2 when :thrice then 3 else Integer(count) end end def queue_adapter ::ActiveJob::Base.queue_adapter end end # rubocop: enable Style/ClassLength # @private class HaveEnqueuedJob < Base def initialize(job) super() @job = job end def matches?(proc) raise ArgumentError, "have_enqueued_job and enqueue_job only support block expectations" unless Proc === proc original_enqueued_jobs_count = queue_adapter.enqueued_jobs.count proc.call in_block_jobs = queue_adapter.enqueued_jobs.drop(original_enqueued_jobs_count) check(in_block_jobs) end end # @private class HaveBeenEnqueued < Base def matches?(job) @job = job check(queue_adapter.enqueued_jobs) end end end # @api public # Passes if a job has been enqueued inside block. May chain at_least, at_most or exactly to specify a number of times. # # @example # expect { # HeavyLiftingJob.perform_later # }.to have_enqueued_job # # # Using alias # expect { # HeavyLiftingJob.perform_later # }.to enqueue_job # # expect { # HelloJob.perform_later # HeavyLiftingJob.perform_later # }.to have_enqueued_job(HelloJob).exactly(:once) # # expect { # 3.times { HelloJob.perform_later } # }.to have_enqueued_job(HelloJob).at_least(2).times # # expect { # HelloJob.perform_later # }.to have_enqueued_job(HelloJob).at_most(:twice) # # expect { # HelloJob.perform_later # HeavyLiftingJob.perform_later # }.to have_enqueued_job(HelloJob).and have_enqueued_job(HeavyLiftingJob) # # expect { # HelloJob.set(wait_until: Date.tomorrow.noon, queue: "low").perform_later(42) # }.to have_enqueued_job.with(42).on_queue("low").at(Date.tomorrow.noon) def have_enqueued_job(job = nil) check_active_job_adapter ActiveJob::HaveEnqueuedJob.new(job) end alias_method :enqueue_job, :have_enqueued_job # @api public # Passes if a job has been enqueued. May chain at_least, at_most or exactly to specify a number of times. # # @example # before { ActiveJob::Base.queue_adapter.enqueued_jobs.clear } # # HeavyLiftingJob.perform_later # expect(HeavyLiftingJob).to have_been_enqueued # # HelloJob.perform_later # HeavyLiftingJob.perform_later # expect(HeavyLiftingJob).to have_been_enqueued.exactly(:once) # # 3.times { HelloJob.perform_later } # expect(HelloJob).to have_been_enqueued.at_least(2).times # # HelloJob.perform_later # expect(HelloJob).to enqueue_job(HelloJob).at_most(:twice) # # HelloJob.perform_later # HeavyLiftingJob.perform_later # expect(HelloJob).to have_been_enqueued # expect(HeavyLiftingJob).to have_been_enqueued # # HelloJob.set(wait_until: Date.tomorrow.noon, queue: "low").perform_later(42) # expect(HelloJob).to have_been_enqueued.with(42).on_queue("low").at(Date.tomorrow.noon) def have_been_enqueued check_active_job_adapter ActiveJob::HaveBeenEnqueued.new end private # @private def check_active_job_adapter return if ::ActiveJob::QueueAdapters::TestAdapter === ::ActiveJob::Base.queue_adapter raise StandardError, "To use ActiveJob matchers set `ActiveJob::Base.queue_adapter = :test`" end end end end rspec-rails-3.7.2/lib/rspec/rails/matchers/be_a_new.rb000066400000000000000000000050071320451746500226460ustar00rootroot00000000000000module RSpec module Rails module Matchers # @api private # # Matcher class for `be_a_new`. Should not be instantiated directly. # # @see RSpec::Rails::Matchers#be_a_new class BeANew < RSpec::Matchers::BuiltIn::BaseMatcher # @private def initialize(expected) @expected = expected end # @private def matches?(actual) @actual = actual actual.is_a?(expected) && actual.new_record? && attributes_match?(actual) end # @api public # @see RSpec::Rails::Matchers#be_a_new def with(expected_attributes) attributes.merge!(expected_attributes) self end # @private def failure_message [].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) describe_unmatched_attributes = surface_descriptions_in(unmatched_attributes) if unmatched_attributes.size > 1 message << "attributes #{describe_unmatched_attributes.inspect} were not set on #{actual.inspect}" else message << "attribute #{describe_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| values_match?(value, actual.attributes[key]) end end def unmatched_attributes attributes.stringify_keys.reject do |key, value| values_match?(value, actual.attributes[key]) end end end # @api public # Passes if actual is an instance of `model_class` and returns `true` for # `new_record?`. Typically used to specify instance variables assigned to # views by controller actions # # Use the `with` method to specify the specific attributes to match on the # new record. # # @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 end end rspec-rails-3.7.2/lib/rspec/rails/matchers/be_new_record.rb000066400000000000000000000013131320451746500237000ustar00rootroot00000000000000module RSpec module Rails module Matchers # @private class BeANewRecord < RSpec::Matchers::BuiltIn::BaseMatcher def matches?(actual) actual.new_record? end def failure_message "expected #{actual.inspect} to be a new record, but was persisted" end def failure_message_when_negated "expected #{actual.inspect} to be persisted, but was a new record" end end # @api public # Passes if actual returns `true` for `new_record?`. # # @example # get :new # expect(assigns(:thing)).to be_new_record def be_new_record BeANewRecord.new end end end end rspec-rails-3.7.2/lib/rspec/rails/matchers/be_valid.rb000066400000000000000000000024111320451746500226500ustar00rootroot00000000000000module RSpec module Rails module Matchers # @private class BeValid < RSpec::Matchers::BuiltIn::Be def initialize(*args) @args = args end def matches?(actual) @actual = actual actual.valid?(*@args) end def failure_message message = "expected #{actual.inspect} to be valid" if actual.respond_to?(:errors) errors = if actual.errors.respond_to?(:full_messages) actual.errors.full_messages else actual.errors end message << ", but got errors: #{errors.map(&:to_s).join(', ')}" end message end def failure_message_when_negated "expected #{actual.inspect} not to be valid" end end # @api public # 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 # expect(thing).to be_valid def be_valid(*args) BeValid.new(*args) end end end end rspec-rails-3.7.2/lib/rspec/rails/matchers/have_http_status.rb000066400000000000000000000333551320451746500245030ustar00rootroot00000000000000# The following code inspired and modified from Rails' `assert_response`: # # https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/assertions/response.rb#L22-L38 # # Thank you to all the Rails devs who did the heavy lifting on this! module RSpec module Rails module Matchers # Namespace for various implementations of `have_http_status`. # # @api private module HaveHttpStatus # Instantiates an instance of the proper matcher based on the provided # `target`. # # @param target [Object] expected http status or code # @return response matcher instance def self.matcher_for_status(target) if GenericStatus.valid_statuses.include?(target) GenericStatus.new(target) elsif Symbol === target SymbolicStatus.new(target) else NumericCode.new(target) end end # @api private # Conversion function to coerce the provided object into an # `ActionDispatch::TestResponse`. # # @param obj [Object] object to convert to a response # @return [ActionDispatch::TestResponse] def as_test_response(obj) if ::ActionDispatch::Response === obj ::ActionDispatch::TestResponse.from_response(obj) elsif ::ActionDispatch::TestResponse === obj obj elsif obj.respond_to?(:status_code) && obj.respond_to?(:response_headers) # Acts As Capybara Session # Hack to support `Capybara::Session` without having to load # Capybara or catch `NameError`s for the undefined constants obj = ActionDispatch::Response.new.tap do |resp| resp.status = obj.status_code resp.headers.clear resp.headers.merge!(obj.response_headers) resp.body = obj.body resp.request = ActionDispatch::Request.new({}) end ::ActionDispatch::TestResponse.from_response(obj) else raise TypeError, "Invalid response type: #{obj}" end end module_function :as_test_response # @return [String, nil] a formatted failure message if # `@invalid_response` is present, `nil` otherwise def invalid_response_type_message return unless @invalid_response "expected a response object, but an instance of " \ "#{@invalid_response.class} was received" end # @api private # Provides an implementation for `have_http_status` matching against # numeric http status codes. # # Not intended to be instantiated directly. # # @example # expect(response).to have_http_status(404) # # @see RSpec::Rails::Matchers.have_http_status class NumericCode < RSpec::Matchers::BuiltIn::BaseMatcher include HaveHttpStatus def initialize(code) @expected = code.to_i @actual = nil @invalid_response = nil end # @param [Object] response object providing an http code to match # @return [Boolean] `true` if the numeric code matched the `response` code def matches?(response) test_response = as_test_response(response) @actual = test_response.response_code.to_i expected == @actual rescue TypeError => _ignored @invalid_response = response false end # @return [String] def description "respond with numeric status code #{expected}" end # @return [String] explaining why the match failed def failure_message invalid_response_type_message || "expected the response to have status code #{expected.inspect}" \ " but it was #{actual.inspect}" end # @return [String] explaining why the match failed def failure_message_when_negated invalid_response_type_message || "expected the response not to have status code " \ "#{expected.inspect} but it did" end end # @api private # Provides an implementation for `have_http_status` matching against # Rack symbol http status codes. # # Not intended to be instantiated directly. # # @example # expect(response).to have_http_status(:created) # # @see RSpec::Rails::Matchers.have_http_status # @see https://github.com/rack/rack/blob/master/lib/rack/utils.rb `Rack::Utils::SYMBOL_TO_STATUS_CODE` class SymbolicStatus < RSpec::Matchers::BuiltIn::BaseMatcher include HaveHttpStatus def initialize(status) @expected_status = status @actual = nil @invalid_response = nil set_expected_code! end # @param [Object] response object providing an http code to match # @return [Boolean] `true` if Rack's associated numeric HTTP code matched # the `response` code def matches?(response) test_response = as_test_response(response) @actual = test_response.response_code expected == @actual rescue TypeError => _ignored @invalid_response = response false end # @return [String] def description "respond with status code #{pp_expected}" end # @return [String] explaining why the match failed def failure_message invalid_response_type_message || "expected the response to have status code #{pp_expected} but it" \ " was #{pp_actual}" end # @return [String] explaining why the match failed def failure_message_when_negated invalid_response_type_message || "expected the response not to have status code #{pp_expected} " \ "but it did" end # The initialized expected status symbol attr_reader :expected_status private :expected_status private # @return [Symbol] representing the actual http numeric code def actual_status return unless actual @actual_status ||= compute_status_from(actual) end # Reverse lookup of the Rack status code symbol based on the numeric # http code # # @param code [Fixnum] http status code to look up # @return [Symbol] representing the http numeric code def compute_status_from(code) status, _ = Rack::Utils::SYMBOL_TO_STATUS_CODE.find do |_, c| c == code end status end # @return [String] pretty format the actual response status def pp_actual pp_status(actual_status, actual) end # @return [String] pretty format the expected status and associated code def pp_expected pp_status(expected_status, expected) end # @return [String] pretty format the actual response status def pp_status(status, code) if status "#{status.inspect} (#{code})" else code.to_s end end # Sets `expected` to the numeric http code based on the Rack # `expected_status` status # # @see Rack::Utils::SYMBOL_TO_STATUS_CODE # @raise [ArgumentError] if an associated code could not be found def set_expected_code! @expected ||= Rack::Utils::SYMBOL_TO_STATUS_CODE.fetch(expected_status) do raise ArgumentError, "Invalid HTTP status: #{expected_status.inspect}" end end end # @api private # Provides an implementation for `have_http_status` matching against # `ActionDispatch::TestResponse` http status category queries. # # Not intended to be instantiated directly. # # @example # expect(response).to have_http_status(:success) # expect(response).to have_http_status(:error) # expect(response).to have_http_status(:missing) # expect(response).to have_http_status(:redirect) # # @see RSpec::Rails::Matchers.have_http_status # @see ActionDispatch::TestResponse class GenericStatus < RSpec::Matchers::BuiltIn::BaseMatcher include HaveHttpStatus # @return [Array] of status codes which represent a HTTP status # code "group" # @see https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/test_response.rb `ActionDispatch::TestResponse` def self.valid_statuses [:error, :success, :missing, :redirect] end def initialize(type) unless self.class.valid_statuses.include?(type) raise ArgumentError, "Invalid generic HTTP status: #{type.inspect}" end @expected = type @actual = nil @invalid_response = nil end # @return [Boolean] `true` if Rack's associated numeric HTTP code matched # the `response` code def matches?(response) test_response = as_test_response(response) @actual = test_response.response_code test_response.send("#{expected}?") rescue TypeError => _ignored @invalid_response = response false end # @return [String] def description "respond with #{type_message}" end # @return [String] explaining why the match failed def failure_message invalid_response_type_message || "expected the response to have #{type_message} but it was #{actual}" end # @return [String] explaining why the match failed def failure_message_when_negated invalid_response_type_message || "expected the response not to have #{type_message} but it was #{actual}" end private # @return [String] formating the expected status and associated code(s) def type_message @type_message ||= (expected == :error ? "an error" : "a #{expected}") + " status code (#{type_codes})" end # @return [String] formatting the associated code(s) for the various # status code "groups" # @see https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/test_response.rb `ActionDispatch::TestResponse` # @see https://github.com/rack/rack/blob/master/lib/rack/response.rb `Rack::Response` def type_codes # At the time of this commit the most recent version of # `ActionDispatch::TestResponse` defines the following aliases: # # alias_method :success?, :successful? # alias_method :missing?, :not_found? # alias_method :redirect?, :redirection? # alias_method :error?, :server_error? # # It's parent `ActionDispatch::Response` includes # `Rack::Response::Helpers` which defines the aliased methods as: # # def successful?; status >= 200 && status < 300; end # def redirection?; status >= 300 && status < 400; end # def server_error?; status >= 500 && status < 600; end # def not_found?; status == 404; end # # @see https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/testing/test_response.rb#L17-L27 # @see https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/http/response.rb#L74 # @see https://github.com/rack/rack/blob/ce4a3959/lib/rack/response.rb#L119-L122 @type_codes ||= case expected when :error "5xx" when :success "2xx" when :missing "404" when :redirect "3xx" end end end end # @api public # Passes if `response` has a matching HTTP status code. # # The following symbolic status codes are allowed: # # - `Rack::Utils::SYMBOL_TO_STATUS_CODE` # - One of the defined `ActionDispatch::TestResponse` aliases: # - `:error` # - `:missing` # - `:redirect` # - `:success` # # @example Accepts numeric and symbol statuses # expect(response).to have_http_status(404) # expect(response).to have_http_status(:created) # expect(response).to have_http_status(:success) # expect(response).to have_http_status(:error) # expect(response).to have_http_status(:missing) # expect(response).to have_http_status(:redirect) # # @example Works with standard `response` objects and Capybara's `page` # expect(response).to have_http_status(404) # expect(page).to have_http_status(:created) # # @see https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/test_response.rb `ActionDispatch::TestResponse` # @see https://github.com/rack/rack/blob/master/lib/rack/utils.rb `Rack::Utils::SYMBOL_TO_STATUS_CODE` def have_http_status(target) raise ArgumentError, "Invalid HTTP status: nil" unless target HaveHttpStatus.matcher_for_status(target) end end end end rspec-rails-3.7.2/lib/rspec/rails/matchers/have_rendered.rb000066400000000000000000000040751320451746500237060ustar00rootroot00000000000000module RSpec module Rails module Matchers # Matcher for template rendering. module RenderTemplate # @private class RenderTemplateMatcher < RSpec::Matchers::BuiltIn::BaseMatcher def initialize(scope, expected, message = nil) @expected = Symbol === expected ? expected.to_s : expected @message = message @scope = scope @redirect_is = nil end # @api private def matches?(*) match_check = match_unless_raises ActiveSupport::TestCase::Assertion do @scope.assert_template expected, @message end check_redirect unless match_check match_check end # Uses normalize_argument_to_redirection to find and format # the redirect location. normalize_argument_to_redirection is private # in ActionDispatch::Assertions::ResponseAssertions so we call it # here using #send. This will keep the error message format consistent # @api private def check_redirect response = @scope.response return unless response.respond_to?(:redirect?) && response.redirect? @redirect_is = @scope.send(:normalize_argument_to_redirection, response.location) end # @api private def failure_message if @redirect_is rescued_exception.message[/(.*?)( but|$)/, 1] + " but was a redirect to <#{@redirect_is}>" else rescued_exception.message end end # @api private def failure_message_when_negated "expected not to render #{expected.inspect}, but did" end end # Delegates to `assert_template`. # # @example # expect(response).to have_rendered("new") def have_rendered(options, message = nil) RenderTemplateMatcher.new(self, options, message) end alias_method :render_template, :have_rendered end end end end rspec-rails-3.7.2/lib/rspec/rails/matchers/redirect_to.rb000066400000000000000000000017001320451746500234060ustar00rootroot00000000000000module RSpec module Rails module Matchers # Matcher for redirects. module RedirectTo # @private class RedirectTo < RSpec::Matchers::BuiltIn::BaseMatcher def initialize(scope, expected) @expected = expected @scope = scope end def matches?(_) match_unless_raises ActiveSupport::TestCase::Assertion do @scope.assert_redirected_to(@expected) end end def failure_message rescued_exception.message end def failure_message_when_negated "expected not to redirect to #{@expected.inspect}, but did" end end # Delegates to `assert_redirected_to`. # # @example # expect(response).to redirect_to(:action => "new") def redirect_to(target) RedirectTo.new(self, target) end end end end end rspec-rails-3.7.2/lib/rspec/rails/matchers/relation_match_array.rb000066400000000000000000000002451320451746500252750ustar00rootroot00000000000000if defined?(ActiveRecord::Relation) RSpec::Matchers::BuiltIn::OperatorMatcher.register(ActiveRecord::Relation, '=~', RSpec::Matchers::BuiltIn::ContainExactly) end rspec-rails-3.7.2/lib/rspec/rails/matchers/routing_matchers.rb000066400000000000000000000101071320451746500244610ustar00rootroot00000000000000module RSpec module Rails module Matchers # Matchers to help with specs for routing code. module RoutingMatchers extend RSpec::Matchers::DSL # @private 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 def matches?(verb_to_path_map) @actual = 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_nested_query(query) ) end end def failure_message rescued_exception.message end def failure_message_when_negated "expected #{@actual.inspect} not to route to #{@expected.inspect}" 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 # # expect(:get => "/things/special").to route_to( # :controller => "things", # :action => "special" # ) # # expect(:get => "/things/special").to 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 # @private class BeRoutableMatcher < RSpec::Matchers::BuiltIn::BaseMatcher def initialize(scope) @scope = scope end 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 "expected #{@actual.inspect} to be routable" end def failure_message_when_negated "expected #{@actual.inspect} not to be routable, but it routes to #{@routing_options.inspect}" end def description "be routable" 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. # expect(:get => "/a/path").to be_routable # expect(:post => "/another/path").to be_routable # expect(:put => "/yet/another/path").to be_routable def be_routable BeRoutableMatcher.new(self) end # Helpers for matching different route types. module RouteHelpers # @!method get # @!method post # @!method put # @!method patch # @!method delete # @!method options # @!method head # # Shorthand method for matching this type of route. %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 end end rspec-rails-3.7.2/lib/rspec/rails/tasks/000077500000000000000000000000001320451746500200775ustar00rootroot00000000000000rspec-rails-3.7.2/lib/rspec/rails/tasks/rspec.rake000066400000000000000000000031731320451746500220630ustar00rootroot00000000000000require 'rspec/core/rake_task' if default = Rake.application.instance_variable_get('@tasks')['default'] default.prerequisites.delete('test') end task :default => :spec task :stats => "spec:statsetup" desc "Run all specs in spec directory (excluding plugin specs)" RSpec::Core::RakeTask.new(:spec => "spec:prepare") namespace :spec do types = begin dirs = Dir['./spec/**/*_spec.rb']. map { |f| f.sub(/^\.\/(spec\/\w+)\/.*/, '\\1') }. uniq. select { |f| File.directory?(f) } Hash[dirs.map { |d| [d.split('/').last, d] }] end task :prepare do ENV['RACK_ENV'] = ENV['RAILS_ENV'] = 'test' if Rails.configuration.generators.options[:rails][:orm] == :active_record if Rake::Task.task_defined?("test:prepare") Rake::Task["test:prepare"].invoke end end end types.each do |type, dir| desc "Run the code examples in #{dir}" RSpec::Core::RakeTask.new(type => "spec:prepare") 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:prepare") 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-3.7.2/lib/rspec/rails/vendor/000077500000000000000000000000001320451746500202475ustar00rootroot00000000000000rspec-rails-3.7.2/lib/rspec/rails/vendor/capybara.rb000066400000000000000000000022211320451746500223530ustar00rootroot00000000000000begin require 'capybara/rspec' rescue LoadError end begin require 'capybara/rails' rescue LoadError end if defined?(Capybara) require 'rspec/support/comparable_version' unless RSpec::Support::ComparableVersion.new(Capybara::VERSION) >= '2.2.0' raise "You are using capybara #{Capybara::VERSION}. RSpec requires >= 2.2.0." end RSpec.configure do |c| if defined?(Capybara::DSL) c.include Capybara::DSL, :type => :feature if defined?(ActionPack) && ActionPack::VERSION::STRING >= "5.1" c.include Capybara::DSL, :type => :system end 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, :type => :feature c.include Capybara::RSpecMatchers, :type => :system end unless defined?(Capybara::RSpecMatchers) || defined?(Capybara::DSL) c.include Capybara, :type => :request c.include Capybara, :type => :controller end end end rspec-rails-3.7.2/lib/rspec/rails/version.rb000066400000000000000000000003121320451746500207600ustar00rootroot00000000000000module RSpec module Rails # Version information for RSpec Rails. module Version # Current version of RSpec Rails, in semantic versioning format. STRING = '3.7.2' end end end rspec-rails-3.7.2/lib/rspec/rails/view_assigns.rb000066400000000000000000000025461320451746500220070ustar00rootroot00000000000000module RSpec module Rails # Helpers for making instance variables available to views. 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 # Compat-shim for AbstractController::Rendering#view_assigns # # _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. def view_assigns super.merge(_encapsulated_assigns) rescue _assigns end # @private def _assigns super.merge(_encapsulated_assigns) end private def _encapsulated_assigns @_encapsulated_assigns ||= {} end end end end rspec-rails-3.7.2/lib/rspec/rails/view_path_builder.rb000066400000000000000000000021621320451746500227740ustar00rootroot00000000000000module RSpec module Rails # Builds paths for view specs using a particular route set. class ViewPathBuilder def initialize(route_set) self.class.send(:include, route_set.url_helpers) end # Given a hash of parameters, build a view path, if possible. # Returns nil if no path can be built from the given params. # # @example # # path can be built because all required params are present in the hash # view_path_builder = ViewPathBuilder.new(::Rails.application.routes) # view_path_builder.path_for({ :controller => 'posts', :action => 'show', :id => '54' }) # # => "/post/54" # # @example # # path cannot be built because the params are missing a required element (:id) # view_path_builder.path_for({ :controller => 'posts', :action => 'delete' }) # # => ActionController::UrlGenerationError: No route matches {:action=>"delete", :controller=>"posts"} def path_for(path_params) url_for(path_params.merge(:only_path => true)) rescue => e e.message end end end end rspec-rails-3.7.2/lib/rspec/rails/view_rendering.rb000066400000000000000000000102621320451746500223070ustar00rootroot00000000000000require 'action_view/testing/resolvers' module RSpec module Rails # @api public # Helpers for optionally rendering views in controller specs. module ViewRendering extend ActiveSupport::Concern # @!attribute [r] # Returns the controller object instance under test. attr_reader :controller # @private attr_writer :controller private :controller= # DSL methods module ClassMethods # @see RSpec::Rails::ControllerExampleGroup def render_views(true_or_false = true) @render_views = true_or_false end # @api private def render_views? return @render_views if defined?(@render_views) if superclass.respond_to?(:render_views?) superclass.render_views? else RSpec.configuration.render_views? end end end # @api private def render_views? self.class.render_views? || !controller.class.respond_to?(:view_paths) end # @private class EmptyTemplateResolver def self.build(path) if path.is_a?(::ActionView::Resolver) ResolverDecorator.new(path) else FileSystemResolver.new(path) end end def self.nullify_template_rendering(templates) templates.map do |template| ::ActionView::Template.new( "", template.identifier, EmptyTemplateHandler, :virtual_path => template.virtual_path, :format => template.formats ) end end # Delegates all methods to the submitted resolver and for all methods # that return a collection of `ActionView::Template` instances, return # templates with modified source # # @private class ResolverDecorator def initialize(resolver) @resolver = resolver end def method_missing(name, *args, &block) result = @resolver.send(name, *args, &block) nullify_templates(result) end private def nullify_templates(collection) return collection unless collection.is_a?(Enumerable) return collection unless collection.all? { |element| element.is_a?(::ActionView::Template) } EmptyTemplateResolver.nullify_template_rendering(collection) end end # Delegates find_templates to the submitted path set and then returns # templates with modified source # # @private class FileSystemResolver < ::ActionView::FileSystemResolver private def find_templates(*args) templates = super EmptyTemplateResolver.nullify_template_rendering(templates) end end end # @private class EmptyTemplateHandler def self.call(_template) ::Rails.logger.info(" Template rendering was prevented by rspec-rails. Use `render_views` to verify rendered view contents if necessary.") %("") end end # Used to null out view rendering in controller specs. # # @private module EmptyTemplates def prepend_view_path(new_path) lookup_context.view_paths.unshift(*_path_decorator(*new_path)) end def append_view_path(new_path) lookup_context.view_paths.push(*_path_decorator(*new_path)) end private def _path_decorator(*paths) paths.map { |path| EmptyTemplateResolver.build(path) } end end # @private RESOLVER_CACHE = Hash.new do |hash, path| hash[path] = EmptyTemplateResolver.build(path) end included do before do unless render_views? @_original_path_set = controller.class.view_paths path_set = @_original_path_set.map { |resolver| RESOLVER_CACHE[resolver.to_s] } controller.class.view_paths = path_set controller.extend(EmptyTemplates) end end after do controller.class.view_paths = @_original_path_set unless render_views? end end end end end rspec-rails-3.7.2/lib/rspec/rails/view_spec_methods.rb000066400000000000000000000035561320451746500230170ustar00rootroot00000000000000module RSpec module Rails # Adds methods (generally to ActionView::TestCase::TestController). # Intended for use in view specs. module ViewSpecMethods module_function # Adds methods `extra_params=` and `extra_params` to the indicated class. # When class is `::ActionView::TestCase::TestController`, these methods # are exposed in view specs on the `controller` object. def add_to(klass) return if klass.method_defined?(:extra_params) && klass.method_defined?(:extra_params=) klass.module_exec do # Set any extra parameters that rendering a URL for this view # would require. # # @example # # # In "spec/views/widgets/show.html.erb_spec.rb": # before do # widget = Widget.create!(:name => "slicer") # controller.extra_params = { :id => widget.id } # end def extra_params=(hash) @extra_params = hash request.path = ViewPathBuilder.new(::Rails.application.routes).path_for( extra_params.merge(request.path_parameters) ) end # Use to read extra parameters that are set in the view spec. # # @example # # # After the before in the above example: # controller.extra_params # # => { :id => 4 } def extra_params @extra_params ||= {} @extra_params.dup.freeze end end end # Removes methods `extra_params=` and `extra_params` from the indicated class. def remove_from(klass) klass.module_exec do undef extra_params= if klass.method_defined?(:extra_params=) undef extra_params if klass.method_defined?(:extra_params) end end end end end rspec-rails-3.7.2/maintenance-branch000066400000000000000000000000201320451746500174060ustar00rootroot000000000000003-7-maintenance rspec-rails-3.7.2/rspec-rails.gemspec000066400000000000000000000035061320451746500175530ustar00rootroot00000000000000# -*- 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", "Andy Lindeman"] s.email = "rspec@googlegroups.com" s.homepage = "https://github.com/rspec/rspec-rails" s.summary = "RSpec for Rails" s.description = "rspec-rails is a testing framework for Rails 3+." s.files = `git ls-files -- lib/*`.split("\n") s.files += %w[README.md LICENSE.md Changelog.md Capybara.md .yardopts .document] s.test_files = [] s.rdoc_options = ["--charset=UTF-8"] s.require_path = "lib" private_key = File.expand_path('~/.gem/rspec-gem-private_key.pem') if File.exist?(private_key) s.signing_key = private_key s.cert_chain = [File.expand_path('~/.gem/rspec-gem-public_cert.pem')] end version_string = ['>= 3.0'] if RUBY_VERSION <= '1.8.7' && ENV['RAILS_VERSION'] != '3-2-stable' version_string << '!= 3.2.22.1' end s.add_runtime_dependency %q, version_string s.add_runtime_dependency %q, version_string s.add_runtime_dependency %q, version_string %w[core expectations mocks support].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 'cucumber', '~> 1.3.5' s.add_development_dependency 'aruba', '~> 0.5.4' s.add_development_dependency 'ammeter', '~> 1.1.2' end rspec-rails-3.7.2/script/000077500000000000000000000000001320451746500152625ustar00rootroot00000000000000rspec-rails-3.7.2/script/after_update_travis_build.sh000077500000000000000000000001321320451746500230270ustar00rootroot00000000000000#!/bin/bash set -e echo "Restoring custom Travis config" mv .travis.yml{.update_backup,} rspec-rails-3.7.2/script/before_update_travis_build.sh000077500000000000000000000001331320451746500231710ustar00rootroot00000000000000#!/bin/bash set -e echo "Backing up custom Travis config" mv .travis.yml{,.update_backup} rspec-rails-3.7.2/script/clone_all_rspec_repos000077500000000000000000000010661320451746500215470ustar00rootroot00000000000000#!/bin/bash # This file was generated on 2017-09-15T10:18:21+09:00 from the rspec-dev repo. # DO NOT modify it by hand as your changes will get lost the next time it is generated. set -e source script/functions.sh if is_mri; then pushd .. clone_repo "rspec" clone_repo "rspec-core" clone_repo "rspec-expectations" clone_repo "rspec-mocks" clone_repo "rspec-rails" if rspec_support_compatible; then clone_repo "rspec-support" fi popd else echo "Not cloning all repos since we are not on MRI and they are only needed for the MRI build" fi rspec-rails-3.7.2/script/custom_build_functions.sh000066400000000000000000000010311320451746500223720ustar00rootroot00000000000000function run_cukes { if is_mri_192_plus; then bin/rake acceptance --trace return $? else return 0 fi } # rspec-rails depends on all of the other rspec repos. Conversely, none of the # other repos have any dependencies with rspec-rails directly. If the other # repos have issues, the rspec-rails suite and cukes would fail exposing them. # Since we are already implicitly testing them we do not need to run their spec # suites explicitly. function run_all_spec_suites { fold "one-by-one specs" run_specs_one_by_one } rspec-rails-3.7.2/script/download-ruby-debug-19-dependencies000077500000000000000000000002751320451746500237410ustar00rootroot00000000000000mkdir -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-3.7.2/script/functions.sh000066400000000000000000000137271320451746500176400ustar00rootroot00000000000000# This file was generated on 2017-09-15T10:18:21+09:00 from the rspec-dev repo. # DO NOT modify it by hand as your changes will get lost the next time it is generated. SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" source $SCRIPT_DIR/travis_functions.sh source $SCRIPT_DIR/predicate_functions.sh # If JRUBY_OPTS isn't set, use these. # see http://docs.travis-ci.com/user/ci-environment/ export JRUBY_OPTS=${JRUBY_OPTS:-"--server -Xcompile.invokedynamic=false"} SPECS_HAVE_RUN_FILE=specs.out MAINTENANCE_BRANCH=`cat maintenance-branch` # Don't allow rubygems to pollute what's loaded. Also, things boot faster # without the extra load time of rubygems. Only works on MRI Ruby 1.9+ if is_mri_192_plus; then export RUBYOPT="--disable=gem" fi function clone_repo { if [ ! -d $1 ]; then # don't clone if the dir is already there travis_retry eval "git clone git://github.com/rspec/$1 --depth 1 --branch $MAINTENANCE_BRANCH" fi; } function run_specs_and_record_done { local rspec_bin=bin/rspec # rspec-core needs to run with a special script that loads simplecov first, # so that it can instrument rspec-core's code before rspec-core has been loaded. if [ -f script/rspec_with_simplecov ] && is_mri; then rspec_bin=script/rspec_with_simplecov fi; echo "${PWD}/bin/rspec" $rspec_bin spec --backtrace --format progress --profile --format progress --out $SPECS_HAVE_RUN_FILE } function run_cukes { if [ -d features ]; then # force jRuby to use client mode JVM or a compilation mode thats as close as possible, # idea taken from https://github.com/jruby/jruby/wiki/Improving-startup-time # # Note that we delay setting this until we run the cukes because we've seen # spec failures in our spec suite due to problems with this mode. export JAVA_OPTS='-client -XX:+TieredCompilation -XX:TieredStopAtLevel=1' echo "${PWD}/bin/cucumber" if is_mri_192; then # For some reason we get SystemStackError on 1.9.2 when using # the bin/cucumber approach below. That approach is faster # (as it avoids the bundler tax), so we use it on rubies where we can. bundle exec cucumber --strict elif is_jruby; then # For some reason JRuby doesn't like our improved bundler setup RUBYOPT="-I${PWD}/../bundle -rbundler/setup" \ PATH="${PWD}/bin:$PATH" \ bin/cucumber --strict else # Prepare RUBYOPT for scenarios that are shelling out to ruby, # and PATH for those that are using `rspec` or `rake`. RUBYOPT="${RUBYOPT} -I${PWD}/../bundle -rbundler/setup" \ PATH="${PWD}/bin:$PATH" \ bin/cucumber --strict fi fi } function run_specs_one_by_one { echo "Running each spec file, one-by-one..." for file in `find spec -iname '*_spec.rb'`; do echo "Running $file" bin/rspec $file -b --format progress done } function run_spec_suite_for { if [ ! -f ../$1/$SPECS_HAVE_RUN_FILE ]; then # don't rerun specs that have already run if [ -d ../$1 ]; then echo "Running specs for $1" pushd ../$1 unset BUNDLE_GEMFILE bundle_install_flags=`cat .travis.yml | grep bundler_args | tr -d '"' | grep -o " .*"` if is_mri_192_plus; then travis_retry eval "RUBYOPT=$RUBYOPT:'--enable rubygems' bundle install $bundle_install_flags" else travis_retry eval "bundle install $bundle_install_flags" fi run_specs_and_record_done popd else echo "" echo "WARNING: The ../$1 directory does not exist. Usually the" echo "travis build cds into that directory and run the specs to" echo "ensure the specs still pass with your latest changes, but" echo "we are going to skip that step." echo "" fi; fi; } function check_binstubs { echo "Checking required binstubs" local success=0 local binstubs="" local gems="" if [ ! -x ./bin/rspec ]; then binstubs="$binstubs bin/rspec" gems="$gems rspec-core" success=1 fi if [ ! -x ./bin/rake ]; then binstubs="$binstubs bin/rake" gems="$gems rake" success=1 fi if [ -d features ]; then if [ ! -x ./bin/cucumber ]; then binstubs="$binstubs bin/cucumber" gems="$gems cucumber" success=1 fi fi if [ $success -eq 1 ]; then echo echo "Missing binstubs:$binstubs" echo "Install missing binstubs using one of the following:" echo echo " # Create the missing binstubs" echo " $ bundle binstubs$gems" echo echo " # To binstub all gems" echo " $ bundle install --binstubs" echo echo " # To binstub all gems and avoid loading bundler" echo " $ bundle install --binstubs --standalone" fi return $success } function check_documentation_coverage { echo "bin/yard stats --list-undoc" bin/yard stats --list-undoc | ruby -e " while line = gets has_warnings ||= line.start_with?('[warn]:') coverage ||= line[/([\d\.]+)% documented/, 1] puts line end unless Float(coverage) == 100 puts \"\n\nMissing documentation coverage (currently at #{coverage}%)\" exit(1) end if has_warnings puts \"\n\nYARD emitted documentation warnings.\" exit(1) end " # Some warnings only show up when generating docs, so do that as well. bin/yard doc --no-cache | ruby -e " while line = gets has_warnings ||= line.start_with?('[warn]:') has_errors ||= line.start_with?('[error]:') puts line end if has_warnings || has_errors puts \"\n\nYARD emitted documentation warnings or errors.\" exit(1) end " } function check_style_and_lint { echo "bin/rubocop lib" bin/rubocop lib } function run_all_spec_suites { fold "rspec-core specs" run_spec_suite_for "rspec-core" fold "rspec-expectations specs" run_spec_suite_for "rspec-expectations" fold "rspec-mocks specs" run_spec_suite_for "rspec-mocks" fold "rspec-rails specs" run_spec_suite_for "rspec-rails" if rspec_support_compatible; then fold "rspec-support specs" run_spec_suite_for "rspec-support" fi } rspec-rails-3.7.2/script/predicate_functions.sh000066400000000000000000000033661320451746500216560ustar00rootroot00000000000000# This file was generated on 2017-09-15T10:18:21+09:00 from the rspec-dev repo. # DO NOT modify it by hand as your changes will get lost the next time it is generated. function is_mri { if ruby -e "exit(!defined?(RUBY_ENGINE) || RUBY_ENGINE == 'ruby')"; then # RUBY_ENGINE only returns 'ruby' on MRI. # MRI 1.8.7 lacks the constant but all other rubies have it (including JRuby in 1.8 mode) return 0 else return 1 fi; } function is_jruby { if ruby -e "exit(defined?(RUBY_PLATFORM) && RUBY_PLATFORM == 'java')"; then # RUBY_ENGINE only returns 'ruby' on MRI. # MRI 1.8.7 lacks the constant but all other rubies have it (including JRuby in 1.8 mode) return 0 else return 1 fi; } function is_mri_192 { if is_mri; then if ruby -e "exit(RUBY_VERSION == '1.9.2')"; then return 0 else return 1 fi else return 1 fi } function is_mri_192_plus { if is_mri; then if ruby -e "exit(RUBY_VERSION.to_f > 1.8)"; then return 0 else return 1 fi else return 1 fi } function is_mri_2plus { if is_mri; then if ruby -e "exit(RUBY_VERSION.to_f > 2.0)"; then return 0 else return 1 fi else return 1 fi } function rspec_support_compatible { if [ "$MAINTENANCE_BRANCH" != "2-99-maintenance" ] && [ "$MAINTENANCE_BRANCH" != "2-14-maintenance" ]; then return 0 else return 1 fi } function additional_specs_available { type run_additional_specs > /dev/null 2>&1 return $? } function documentation_enforced { if [ -x ./bin/yard ]; then if is_mri_2plus; then return 0 else return 1 fi else return 1 fi } function style_and_lint_enforced { if [ -x ./bin/rubocop ]; then return 0 else return 1 fi } rspec-rails-3.7.2/script/run_build000077500000000000000000000015531320451746500171770ustar00rootroot00000000000000#!/bin/bash # This file was generated on 2017-09-15T10:18:21+09:00 from the rspec-dev repo. # DO NOT modify it by hand as your changes will get lost the next time it is generated. set -e source script/functions.sh # Allow repos to override the default functions and add their own if [ -f script/custom_build_functions.sh ]; then source script/custom_build_functions.sh fi fold "binstub check" check_binstubs fold "specs" run_specs_and_record_done if additional_specs_available; then fold "additional specs" run_additional_specs fi fold "cukes" run_cukes if documentation_enforced; then fold "doc check" check_documentation_coverage fi if style_and_lint_enforced; then fold "rubocop" check_style_and_lint fi if is_mri; then fold "one-by-one specs" run_specs_one_by_one run_all_spec_suites else echo "Skipping the rest of the build on non-MRI rubies" fi rspec-rails-3.7.2/script/travis_functions.sh000066400000000000000000000037671320451746500212330ustar00rootroot00000000000000# This file was generated on 2017-09-15T10:18:21+09:00 from the rspec-dev repo. # DO NOT modify it by hand as your changes will get lost the next time it is generated. # Taken from: # https://github.com/travis-ci/travis-build/blob/e9314616e182a23e6a280199cd9070bfc7cae548/lib/travis/build/script/templates/header.sh#L34-L53 travis_retry() { local result=0 local count=1 while [ $count -le 3 ]; do [ $result -ne 0 ] && { echo -e "\n\033[33;1mThe command \"$@\" failed. Retrying, $count of 3.\033[0m\n" >&2 } "$@" result=$? [ $result -eq 0 ] && break count=$(($count + 1)) sleep 1 done [ $count -eq 3 ] && { echo "\n\033[33;1mThe command \"$@\" failed 3 times.\033[0m\n" >&2 } return $result } # Taken from https://github.com/vcr/vcr/commit/fa96819c92b783ec0c794f788183e170e4f684b2 # and https://github.com/vcr/vcr/commit/040aaac5370c68cd13c847c076749cd547a6f9b1 nano_cmd="$(type -p gdate date | head -1)" nano_format="+%s%N" [ "$(uname -s)" != "Darwin" ] || nano_format="${nano_format/%N/000000000}" travis_time_start() { travis_timer_id=$(printf %08x $(( RANDOM * RANDOM ))) travis_start_time=$($nano_cmd -u "$nano_format") printf "travis_time:start:%s\r\e[0m" $travis_timer_id } travis_time_finish() { local travis_end_time=$($nano_cmd -u "$nano_format") local duration=$(($travis_end_time-$travis_start_time)) printf "travis_time:end:%s:start=%s,finish=%s,duration=%s\r\e[0m" \ $travis_timer_id $travis_start_time $travis_end_time $duration } fold() { local name="$1" local status=0 shift 1 if [ -n "$TRAVIS" ]; then printf "travis_fold:start:%s\r\e[0m" "$name" travis_time_start else echo "============= Starting $name ===============" fi "$@" status=$? [ -z "$TRAVIS" ] || travis_time_finish if [ "$status" -eq 0 ]; then if [ -n "$TRAVIS" ]; then printf "travis_fold:end:%s\r\e[0m" "$name" else echo "============= Ending $name ===============" fi else STATUS="$status" fi return $status } rspec-rails-3.7.2/spec/000077500000000000000000000000001320451746500147105ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/000077500000000000000000000000001320451746500170615ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/rspec/000077500000000000000000000000001320451746500201755ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/rspec/controller/000077500000000000000000000000001320451746500223605ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/rspec/controller/controller_generator_spec.rb000066400000000000000000000060671320451746500301610ustar00rootroot00000000000000# Generators are not automatically loaded by Rails require 'generators/rspec/controller/controller_generator' require 'support/generators' RSpec.describe Rspec::Generators::ControllerGenerator, :type => :generator do setup_default_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 { is_expected.to exist } it { is_expected.to contain(/require 'rails_helper'/) } it { is_expected.to contain(/^RSpec.describe PostsController, #{type_metatag(:controller)}/) } end end describe 'skipped with a flag' do before do run_generator %w(posts --no-controller_specs) end it { is_expected.not_to 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 { is_expected.not_to 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 { is_expected.not_to 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 { is_expected.not_to 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 { is_expected.to exist } it { is_expected.to contain(/require 'rails_helper'/) } it { is_expected.to contain(/^RSpec.describe "posts\/index.html.erb", #{type_metatag(:view)}/) } end describe 'show.html.erb' do subject { file('spec/views/posts/show.html.erb_spec.rb') } it { is_expected.to exist } it { is_expected.to contain(/require 'rails_helper'/) } it { is_expected.to contain(/^RSpec.describe "posts\/show.html.erb", #{type_metatag(:view)}/) } 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 { is_expected.to exist } it { is_expected.to contain(/require 'rails_helper'/) } it { is_expected.to contain(/^RSpec.describe "posts\/index.html.haml", #{type_metatag(:view)}/) } end end end end end rspec-rails-3.7.2/spec/generators/rspec/feature/000077500000000000000000000000001320451746500216305ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/rspec/feature/feature_generator_spec.rb000066400000000000000000000032601320451746500266710ustar00rootroot00000000000000# Generators are not automatically loaded by rails require 'generators/rspec/feature/feature_generator' require 'support/generators' RSpec.describe Rspec::Generators::FeatureGenerator, :type => :generator do setup_default_destination describe 'feature specs' do describe 'are generated independently from the command line' do before do run_generator %w(posts) end describe 'the spec' do subject(:feature_spec) { file('spec/features/posts_spec.rb') } it "exists" do expect(feature_spec).to exist end it "contains 'rails_helper'" do expect(feature_spec).to contain(/require 'rails_helper'/) end it "contains the feature" do expect(feature_spec).to contain(/^RSpec.feature \"Posts\", #{type_metatag(:feature)}/) end end end describe 'are singularized appropriately with the --singularize flag' do before do run_generator %w(posts --singularize) end describe 'the spec' do subject(:feature_spec) { file('spec/features/post_spec.rb') } it "exists with the appropriate filename" do expect(feature_spec).to exist end it "contains the singularized feature" do expect(feature_spec).to contain(/^RSpec.feature \"Post\", #{type_metatag(:feature)}/) end end end describe "are not generated" do before do run_generator %w(posts --no-feature-specs) end describe "the spec" do subject(:feature_spec) { file('spec/features/posts_spec.rb') } it "does not exist" do expect(feature_spec).to_not exist end end end end end rspec-rails-3.7.2/spec/generators/rspec/helper/000077500000000000000000000000001320451746500214545ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/rspec/helper/helper_generator_spec.rb000066400000000000000000000013731320451746500263440ustar00rootroot00000000000000# Generators are not automatically loaded by Rails require 'generators/rspec/helper/helper_generator' require 'support/generators' RSpec.describe Rspec::Generators::HelperGenerator, :type => :generator do setup_default_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 { is_expected.to exist } it { is_expected.to contain(/require 'rails_helper'/) } it { is_expected.to contain(/^RSpec.describe PostsHelper, #{type_metatag(:helper)}/) } end end describe 'skipped with a flag' do before do run_generator %w(posts --no-helper_specs) end it { is_expected.not_to exist } end end rspec-rails-3.7.2/spec/generators/rspec/install/000077500000000000000000000000001320451746500216435ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/rspec/install/install_generator_spec.rb000066400000000000000000000067351320451746500267310ustar00rootroot00000000000000# Generators are not automatically loaded by Rails require 'generators/rspec/install/install_generator' require 'support/generators' RSpec.describe Rspec::Generators::InstallGenerator, :type => :generator do def use_active_record_migration match(/ActiveRecord::Migration\./m) end def check_pending_migrations match(/ActiveRecord::Migration\.check_pending!/m) end def content_for(file_name) File.read(file(file_name)) end def have_a_fixture_path match(/config\.fixture_path/m) end def maintain_test_schema match(/ActiveRecord::Migration\.maintain_test_schema!/m) end def require_rspec_rails match(/^require 'rspec\/rails'$/m) end def have_transactional_fixtures_enabled? match(/config\.use_transactional_fixtures/m) end def filter_rails_from_backtrace match(/config\.filter_rails_from_backtrace!/m) end setup_default_destination let(:rails_helper) { content_for('spec/rails_helper.rb') } let(:spec_helper) { content_for('spec/spec_helper.rb') } let(:developmentrb) { content_for('config/environments/development.rb') } it "generates .rspec" do run_generator expect(file('.rspec')).to exist end it "generates spec/spec_helper.rb" do generator_command_notice = / This file was generated by the `rails generate rspec:install` command./m run_generator expect(spec_helper).to match(generator_command_notice) end it "does not configure warnings in the spec/spec_helper.rb" do run_generator expect(spec_helper).not_to match(/\bconfig.warnings\b/m) end context "generates spec/rails_helper.rb" do specify "requiring rspec/rails" do run_generator expect(rails_helper).to require_rspec_rails end specify "with transactional fixtures" do run_generator expect(rails_helper).to have_a_fixture_path end specify "with default fixture path" do run_generator expect(rails_helper).to have_transactional_fixtures_enabled? end specify "excluding rails gems from the backtrace" do run_generator expect(rails_helper).to filter_rails_from_backtrace end if RSpec::Rails::FeatureCheck.can_maintain_test_schema? specify "checking for maintaining the schema" do run_generator expect(rails_helper).to maintain_test_schema end elsif RSpec::Rails::FeatureCheck.can_check_pending_migrations? specify "checking for pending migrations" do run_generator expect(rails_helper).to check_pending_migrations end else specify "without a check for pending migrations" do run_generator expect(rails_helper).not_to use_active_record_migration end end end context "generates spec/rails_helper.rb", "without ActiveRecord available" do before do hide_const("ActiveRecord") end it "requires rspec/rails" do run_generator expect(rails_helper).to require_rspec_rails end it "does not include config.fixture_path" do run_generator expect(rails_helper).not_to have_a_fixture_path end it "does not include config.use_transactional_fixtures" do run_generator expect(rails_helper).not_to have_transactional_fixtures_enabled? end it "does not check use active record migration options" do run_generator expect(rails_helper).not_to use_active_record_migration expect(rails_helper).not_to maintain_test_schema expect(rails_helper).not_to check_pending_migrations end end end rspec-rails-3.7.2/spec/generators/rspec/integration/000077500000000000000000000000001320451746500225205ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/rspec/integration/integration_generator_spec.rb000066400000000000000000000004521320451746500304510ustar00rootroot00000000000000# Generators are not automatically loaded by Rails require 'generators/rspec/integration/integration_generator' require 'support/generators' RSpec.describe Rspec::Generators::IntegrationGenerator, :type => :generator do setup_default_destination it_behaves_like "a request spec generator" end rspec-rails-3.7.2/spec/generators/rspec/job/000077500000000000000000000000001320451746500207475ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/rspec/job/job_generator_spec.rb000066400000000000000000000011131320451746500251220ustar00rootroot00000000000000# Generators are not automatically loaded by Rails require 'generators/rspec/job/job_generator' require 'support/generators' RSpec.describe Rspec::Generators::JobGenerator, :type => :generator, :skip => !RSpec::Rails::FeatureCheck.has_active_job? do setup_default_destination describe 'the generated files' do before { run_generator %w(user) } subject { file('spec/jobs/user_job_spec.rb') } it { is_expected.to exist } it { is_expected.to contain(/require 'rails_helper'/) } it { is_expected.to contain(/describe UserJob, #{type_metatag(:job)}/) } end end rspec-rails-3.7.2/spec/generators/rspec/mailer/000077500000000000000000000000001320451746500214465ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/rspec/mailer/mailer_generator_spec.rb000066400000000000000000000042521320451746500263270ustar00rootroot00000000000000# Generators are not automatically loaded by Rails require 'generators/rspec/mailer/mailer_generator' require 'support/generators' RSpec.describe Rspec::Generators::MailerGenerator, :type => :generator do setup_default_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 { is_expected.to exist } it { is_expected.to contain(/require "rails_helper"/) } if Rails.version.to_f >= 5.0 # Rails 5 automatically appends Mailer to the provided constant so we do too it { is_expected.to contain(/^RSpec.describe PostsMailer, #{type_metatag(:mailer)}/) } else it { is_expected.to contain(/^RSpec.describe Posts, #{type_metatag(:mailer)}/) } end it { is_expected.to contain(/describe "index" do/) } it { is_expected.to contain(/describe "show" do/) } end describe 'creates placeholder when no actions specified' do before do run_generator %w(posts) end it { is_expected.to exist } it { is_expected.to contain(/require "rails_helper"/) } it { is_expected.to 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 { is_expected.to exist } it { is_expected.to contain(/Posts#index/) } end describe 'show' do subject { file('spec/fixtures/posts/show') } it { is_expected.to exist } it { is_expected.to contain(/Posts#show/) } end end describe 'a preview is generated for each action', :skip => !RSpec::Rails::FeatureCheck.has_action_mailer_preview? do subject { file('spec/mailers/previews/posts_preview.rb') } before do run_generator %w(posts index show) end it { is_expected.to exist } it { is_expected.to contain(/class PostsPreview < ActionMailer::Preview/) } it { is_expected.to contain(/def index/) } it { is_expected.to contain(/def show/) } end end rspec-rails-3.7.2/spec/generators/rspec/model/000077500000000000000000000000001320451746500212755ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/rspec/model/model_generator_spec.rb000066400000000000000000000025011320451746500260000ustar00rootroot00000000000000# Generators are not automatically loaded by Rails require 'generators/rspec/model/model_generator' require 'support/generators' RSpec.describe Rspec::Generators::ModelGenerator, :type => :generator do setup_default_destination it 'runs both the model and fixture tasks' do gen = generator %w(posts) expect(gen).to receive :create_model_spec expect(gen).to receive :create_fixture_file 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 { is_expected.to exist } it { is_expected.to contain(/require 'rails_helper'/) } it { is_expected.to contain(/^RSpec.describe Posts, #{type_metatag(:model)}/) } end describe 'the fixtures' do subject { file('spec/fixtures/posts.yml') } it { is_expected.to contain(Regexp.new('# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.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 { is_expected.not_to exist } end end end end rspec-rails-3.7.2/spec/generators/rspec/observer/000077500000000000000000000000001320451746500220245ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/rspec/observer/observer_generator_spec.rb000066400000000000000000000010701320451746500272560ustar00rootroot00000000000000# Generators are not automatically loaded by Rails require 'generators/rspec/observer/observer_generator' require 'support/generators' RSpec.describe Rspec::Generators::ObserverGenerator, :type => :generator do setup_default_destination subject { file('spec/models/posts_observer_spec.rb') } before do run_generator %w(posts) end describe 'the spec' do it { is_expected.to exist } it { is_expected.to contain(/require 'rails_helper'/) } it { is_expected.to contain(/^RSpec.describe PostsObserver, #{type_metatag(:observer)}/) } end end rspec-rails-3.7.2/spec/generators/rspec/request/000077500000000000000000000000001320451746500216655ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/rspec/request/request_generator_spec.rb000066400000000000000000000004361320451746500267650ustar00rootroot00000000000000# Generators are not automatically loaded by Rails require 'generators/rspec/request/request_generator' require 'support/generators' RSpec.describe Rspec::Generators::RequestGenerator, :type => :generator do setup_default_destination it_behaves_like "a request spec generator" end rspec-rails-3.7.2/spec/generators/rspec/scaffold/000077500000000000000000000000001320451746500217565ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/rspec/scaffold/scaffold_generator_spec.rb000066400000000000000000000230251320451746500271460ustar00rootroot00000000000000# Generators are not automatically loaded by Rails require 'generators/rspec/scaffold/scaffold_generator' require 'support/generators' RSpec.describe Rspec::Generators::ScaffoldGenerator, :type => :generator do setup_default_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 { is_expected.to contain(/require 'rails_helper'/) } it { is_expected.to contain(/^RSpec.describe PostsController, #{type_metatag(:controller)}/) } it { is_expected.to contain(/GET #new/) } it { is_expected.to contain(/"redirects to the created \w+"/) } it { is_expected.to contain(/display the 'new' template/) } it { is_expected.not_to contain(/"renders a JSON response with the new \w+"/) } it { is_expected.not_to contain(/"renders a JSON response with errors for the new \w+"/) } it { is_expected.to contain(/GET #edit/) } it { is_expected.to contain(/"redirects to the \w+"/) } it { is_expected.to contain(/display the 'edit' template/) } it { is_expected.not_to contain(/"renders a JSON response with the \w+"/) } it { is_expected.not_to contain(/"renders a JSON response with errors for the \w+"/) } it { is_expected.to contain(/"redirects to the \w+ list"/) } end describe 'with --no-controller_specs' do before { run_generator %w(posts --no-controller_specs) } it { is_expected.not_to exist } end describe 'with --api' do before { run_generator %w(posts --api) } it { is_expected.to contain(/require 'rails_helper'/) } it { is_expected.to contain(/^RSpec.describe PostsController, #{type_metatag(:controller)}/) } it { is_expected.not_to contain(/GET #new/) } it { is_expected.not_to contain(/"redirects to the created \w+"/) } it { is_expected.not_to contain(/display the 'new' template/) } it { is_expected.to contain(/"renders a JSON response with the new \w+"/) } it { is_expected.to contain(/"renders a JSON response with errors for the new \w+"/) } it { is_expected.not_to contain(/GET #edit/) } it { is_expected.not_to contain(/"redirects to the \w+"/) } it { is_expected.not_to contain(/display the 'edit' template/) } it { is_expected.to contain(/"renders a JSON response with the \w+"/) } it { is_expected.to contain(/"renders a JSON response with errors for the \w+"/) } it { is_expected.not_to contain(/"redirects to the \w+ list"/) } end end describe 'namespaced controller spec' do subject { file('spec/controllers/admin/posts_controller_spec.rb') } before { run_generator %w(admin/posts) } it { is_expected.to contain(/^RSpec.describe Admin::PostsController, #{type_metatag(:controller)}/)} 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 { is_expected.to exist } it { is_expected.to contain(/require 'rails_helper'/) } it { is_expected.to contain(/^RSpec.describe "(.*)\/edit", #{type_metatag(:view)}/) } it { is_expected.to contain(/it "renders the edit (.*) form"/) } end describe 'index' do subject { file("spec/views/posts/index.html.erb_spec.rb") } it { is_expected.to exist } it { is_expected.to contain(/require 'rails_helper'/) } it { is_expected.to contain(/^RSpec.describe "(.*)\/index", #{type_metatag(:view)}/) } it { is_expected.to contain(/it "renders a list of (.*)"/) } end describe 'new' do subject { file("spec/views/posts/new.html.erb_spec.rb") } it { is_expected.to exist } it { is_expected.to contain(/require 'rails_helper'/) } it { is_expected.to contain(/^RSpec.describe "(.*)\/new", #{type_metatag(:view)}/) } it { is_expected.to contain(/it "renders new (.*) form"/) } end describe 'show' do subject { file("spec/views/posts/show.html.erb_spec.rb") } it { is_expected.to exist } it { is_expected.to contain(/require 'rails_helper'/) } it { is_expected.to contain(/^RSpec.describe "(.*)\/show", #{type_metatag(:view)}/) } it { is_expected.to contain(/it "renders attributes in

"/) } end end describe 'with multiple integer attributes index' do before { run_generator %w(posts upvotes:integer downvotes:integer) } subject { file("spec/views/posts/index.html.erb_spec.rb") } it { is_expected.to exist } it { is_expected.to contain('assert_select "tr>td", :text => 2.to_s, :count => 2') } it { is_expected.to contain('assert_select "tr>td", :text => 3.to_s, :count => 2') } end describe 'with multiple float attributes index' do before { run_generator %w(posts upvotes:float downvotes:float) } subject { file("spec/views/posts/index.html.erb_spec.rb") } it { is_expected.to exist } it { is_expected.to contain('assert_select "tr>td", :text => 2.5.to_s, :count => 2') } it { is_expected.to contain('assert_select "tr>td", :text => 3.5.to_s, :count => 2') } end case when Rails.version.to_f >= 5.1 describe 'with reference attribute' do before { run_generator %w(posts title:string author:references) } describe 'edit' do subject { file("spec/views/posts/edit.html.erb_spec.rb") } it { is_expected.to contain(/assert_select "input\[name=\?\]", "post\[author_id\]/) } it { is_expected.to contain(/assert_select "input\[name=\?\]", "post\[title\]/) } end describe 'new' do subject { file("spec/views/posts/new.html.erb_spec.rb") } it { is_expected.to contain(/assert_select "input\[name=\?\]", "post\[author_id\]"/) } it { is_expected.to contain(/assert_select "input\[name=\?\]", "post\[title\]/) } end end when Rails.version.to_f >= 4.0 describe 'with reference attribute' do before { run_generator %w(posts title:string author:references) } describe 'edit' do subject { file("spec/views/posts/edit.html.erb_spec.rb") } it { is_expected.to contain(/assert_select "input#(.*)_author_id\[name=\?\]", "\1\[author_id\]/) } it { is_expected.to contain(/assert_select "input#(.*)_title\[name=\?\]", "\1\[title\]/) } end describe 'new' do subject { file("spec/views/posts/new.html.erb_spec.rb") } it { is_expected.to contain(/assert_select "input#(.*)_author_id\[name=\?\]", "\1\[author_id\]"/) } it { is_expected.to contain(/assert_select "input#(.*)_title\[name=\?\]", "\1\[title\]/) } end 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 { is_expected.not_to exist } end describe 'index' do subject { file("spec/views/posts/index.html._spec.rb") } it { is_expected.not_to exist } end describe 'new' do subject { file("spec/views/posts/new.html._spec.rb") } it { is_expected.not_to exist } end describe 'show' do subject { file("spec/views/posts/show.html._spec.rb") } it { is_expected.not_to exist } end end describe 'with --api' do before { run_generator %w(posts --api) } describe 'edit' do subject { file("spec/views/posts/edit.html.erb_spec.rb") } it { is_expected.not_to exist } end describe 'index' do subject { file("spec/views/posts/index.html.erb_spec.rb") } it { is_expected.not_to exist } end describe 'new' do subject { file("spec/views/posts/index.html.erb_spec.rb") } it { is_expected.not_to exist } end describe 'show' do subject { file("spec/views/posts/index.html.erb_spec.rb") } it { is_expected.not_to 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 { is_expected.not_to exist } end describe 'index' do subject { file("spec/views/posts/index.html.erb_spec.rb") } it { is_expected.not_to exist } end describe 'new' do subject { file("spec/views/posts/new.html.erb_spec.rb") } it { is_expected.not_to exist } end describe 'show' do subject { file("spec/views/posts/show.html.erb_spec.rb") } it { is_expected.not_to 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 { is_expected.to contain(/require "rails_helper"/) } it { is_expected.to contain(/^RSpec.describe PostsController, #{type_metatag(:routing)}/) } it { is_expected.to contain(/describe "routing"/) } it { is_expected.to contain(/routes to #new/) } it { is_expected.to contain(/routes to #edit/) } end describe 'with --no-routing-specs' do before { run_generator %w(posts --no-routing_specs) } it { is_expected.not_to exist } end describe 'with --api' do before { run_generator %w(posts --api) } it { is_expected.not_to contain(/routes to #new/) } it { is_expected.not_to contain(/routes to #edit/) } end end end rspec-rails-3.7.2/spec/generators/rspec/view/000077500000000000000000000000001320451746500211475ustar00rootroot00000000000000rspec-rails-3.7.2/spec/generators/rspec/view/view_generator_spec.rb000066400000000000000000000025631320451746500255340ustar00rootroot00000000000000# Generators are not automatically loaded by Rails require 'generators/rspec/view/view_generator' require 'support/generators' RSpec.describe Rspec::Generators::ViewGenerator, :type => :generator do setup_default_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| expect(f).to contain(/require 'rails_helper'/) expect(f).to contain(/^RSpec.describe \"posts\/index\", #{type_metatag(:view)}/) 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| expect(f).to contain(/require 'rails_helper'/) expect(f).to contain(/^RSpec.describe \"admin\/posts\/index\", #{type_metatag(:view)}/) 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| expect(f).to contain(/require 'rails_helper'/) expect(f).to contain(/^RSpec.describe \"posts\/index\", #{type_metatag(:view)}/) end end end end rspec-rails-3.7.2/spec/rspec/000077500000000000000000000000001320451746500160245ustar00rootroot00000000000000rspec-rails-3.7.2/spec/rspec/rails/000077500000000000000000000000001320451746500171365ustar00rootroot00000000000000rspec-rails-3.7.2/spec/rspec/rails/active_model_spec.rb000066400000000000000000000022741320451746500231350ustar00rootroot00000000000000RSpec.describe "ActiveModel support" do around do |ex| old_value = RSpec::Mocks.configuration.verify_partial_doubles? ex.run RSpec::Mocks.configuration.verify_partial_doubles = old_value end RSpec.shared_examples_for "stubbing ActiveModel" do before do stub_const 'ActiveRecord' unless defined?(ActiveRecord) end it "allows you to stub `ActiveModel`" do allow(ActiveModel).to receive(:inspect).and_return("stubbed inspect") expect(ActiveModel.inspect).to eq "stubbed inspect" end it 'allows you to stub instances of `ActiveModel`' do klass = Class.new { include ActiveModel::AttributeMethods; attr_accessor :name } model = klass.new allow(model).to receive(:name) { 'stubbed name' } expect(model.name).to eq 'stubbed name' end end context "with partial double verification enabled" do before do RSpec::Mocks.configuration.verify_partial_doubles = true end include_examples "stubbing ActiveModel" end context "with partial double verification disabled" do before do RSpec::Mocks.configuration.verify_partial_doubles = false end include_examples "stubbing ActiveModel" end end rspec-rails-3.7.2/spec/rspec/rails/active_record_spec.rb000066400000000000000000000024631320451746500233130ustar00rootroot00000000000000RSpec.describe "ActiveRecord support" do around do |ex| old_value = RSpec::Mocks.configuration.verify_partial_doubles? ex.run RSpec::Mocks.configuration.verify_partial_doubles = old_value end RSpec.shared_examples_for "stubbing ActiveRecord::Base" do it "allows you to stub `ActiveRecord::Base`" do allow(ActiveRecord::Base).to receive(:inspect).and_return("stubbed inspect") expect(ActiveRecord::Base.inspect).to eq "stubbed inspect" end end RSpec.shared_examples_for "stubbing abstract classes" do it "allows you to stub abstract classes" do klass = Class.new(ActiveRecord::Base) do self.abstract_class = true end allow(klass).to receive(:find).and_return("stubbed find") expect(klass.find(1)).to eq "stubbed find" end end context "with partial double verification enabled" do before do RSpec::Mocks.configuration.verify_partial_doubles = true end include_examples "stubbing ActiveRecord::Base" include_examples "stubbing abstract classes" end context "with partial double verification disabled" do before do RSpec::Mocks.configuration.verify_partial_doubles = false end include_examples "stubbing ActiveRecord::Base" include_examples "stubbing abstract classes" end end rspec-rails-3.7.2/spec/rspec/rails/assertion_adapter_spec.rb000066400000000000000000000024321320451746500242050ustar00rootroot00000000000000require "spec_helper" describe RSpec::Rails::MinitestAssertionAdapter do include RSpec::Rails::MinitestAssertionAdapter RSpec::Rails::Assertions.public_instance_methods.select{|m| m.to_s =~ /^(assert|flunk|refute)/}.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 expect(methods).to include(m) end end end it "does not expose internal methods of Minitest" do expect(methods).not_to include("_assertions") end it "does not expose Minitest's message method" do expect(methods).not_to include("message") end if ::Rails::VERSION::STRING >= '4.0.0' # In Ruby <= 1.8.7 Object#methods returns Strings instead of Symbols. They # are all converted to Symbols to ensure we always compare them correctly. it 'does not leak TestUnit specific methods into the AssertionDelegator' do expect(methods.map(&:to_sym)).to_not include(:build_message) end else it 'includes methods required by TestUnit into the AssertionDelegator' do expect(methods.map(&:to_sym)).to include(:build_message) end end end rspec-rails-3.7.2/spec/rspec/rails/assertion_delegator_spec.rb000066400000000000000000000020141320451746500245270ustar00rootroot00000000000000require "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(RSpec::Rails::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-3.7.2/spec/rspec/rails/configuration_spec.rb000066400000000000000000000206551320451746500233540ustar00rootroot00000000000000require "spec_helper" require 'rspec/support/spec/in_sub_process' RSpec.describe "Configuration" do include RSpec::Support::InSubProcess subject(:config) { RSpec::Core::Configuration.new } before do RSpec::Rails.initialize_configuration(config) end it "adds 'vendor/' to the backtrace exclusions" do expect(config.backtrace_exclusion_patterns).to include(/vendor\//) end it "adds 'lib/rspec/rails' to the backtrace exclusions" do expect( config.backtrace_exclusion_patterns ).to include(%r{lib/rspec/rails}) end shared_examples_for "adds setting" do |accessor, opts| opts ||= {} default_value = opts[:default] alias_setting = opts[:alias_with] query_method = "#{accessor}?".to_sym command_method = "#{accessor}=".to_sym specify "`##{query_method}` is `#{default_value.inspect}` by default" do expect(config.send(query_method)).to be(default_value) end describe "`##{command_method}`" do it "changes `#{query_method}` to the provided value" do expect { config.send(command_method, :a_value) }.to change { config.send(query_method) }.to(:a_value) end it "sets `#{accessor}` to the provided value" do expect { config.send(command_method, :a_value) }.to change { config.send(accessor) }.from(default_value).to(:a_value) end end if alias_setting specify "`##{alias_setting}` is an alias for `#{accessor}`" do expect { config.send(command_method, :a_value) }.to change { config.send(alias_setting) }.to(:a_value) end end end context "adds settings" do include_examples "adds setting", :infer_base_class_for_anonymous_controllers, :default => true include_examples "adds setting", :use_transactional_fixtures, :alias_with => :use_transactional_examples include_examples "adds setting", :use_instantiated_fixtures include_examples "adds setting", :global_fixtures include_examples "adds setting", :fixture_path include_examples "adds setting", :rendering_views specify "`#render_views?` is falsey by default" do expect(config.render_views?).to be_falsey end specify "`#render_views` sets `render_views?` to `true`" do expect { config.render_views }.to change { config.render_views? }.to be(true) end describe "`#render_views=`" do it "sets `render_views?` to the provided value" do expect { config.render_views = false }.to change { config.render_views? }.from(nil).to(false) end it "sets `render_views` to the provided value" do expect { config.render_views = :a_value }.to change { config.render_views? }.to(:a_value) end end end specify "#filter_rails_from_backtrace! adds exclusion patterns for rails gems" do config.filter_rails_from_backtrace! gems = %w[ actionmailer actionpack actionview activemodel activerecord activesupport activejob ] exclusions = config.backtrace_exclusion_patterns.map(&:to_s) aggregate_failures do gems.each { |gem| expect(exclusions).to include(/#{gem}/) } end end describe "#infer_spec_type_from_file_location!" do def in_inferring_type_from_location_environment in_sub_process do RSpec.configuration.infer_spec_type_from_file_location! yield end end shared_examples_for "infers type from location" do |type, location| it "sets the type to `#{type.inspect}` for file path `#{location}`" do in_inferring_type_from_location_environment do allow(RSpec::Core::Metadata).to receive(:relative_path).and_return( "./#{location}/foos_spec.rb" ) group = RSpec.describe("Arbitrary Description") expect(group.metadata).to include(:type => type) end end end include_examples "infers type from location", :controller, "spec/controllers" include_examples "infers type from location", :helper, "spec/helpers" include_examples "infers type from location", :mailer, "spec/mailers" include_examples "infers type from location", :model, "spec/models" include_examples "infers type from location", :request, "spec/requests" include_examples "infers type from location", :request, "spec/integration" include_examples "infers type from location", :request, "spec/api" include_examples "infers type from location", :routing, "spec/routing" include_examples "infers type from location", :view, "spec/views" include_examples "infers type from location", :feature, "spec/features" end it "fixture support is included with metadata `:use_fixtures`" do in_sub_process do RSpec.configuration.global_fixtures = [:foo] RSpec.configuration.fixture_path = "custom/path" group = RSpec.describe("Arbitrary Description", :use_fixtures) expect(group).to respond_to(:fixture_path) expect(group.fixture_path).to eq("custom/path") expect(group.new.respond_to?(:foo, true)).to be(true) end end it "metadata `:type => :controller` sets up controller example groups" do a_controller_class = Class.new stub_const "SomeController", a_controller_class group = RSpec.describe(SomeController, :type => :controller) expect(group.controller_class).to be(a_controller_class) expect(group.new).to be_a(RSpec::Rails::ControllerExampleGroup) end it "metadata `:type => :helper` sets up helper example groups" do a_helper_module = Module.new stub_const "SomeHelper", a_helper_module group = RSpec.describe(SomeHelper, :type => :helper) expect( group.determine_default_helper_class(:ignored) ).to be(a_helper_module) expect(group.new).to be_a(RSpec::Rails::HelperExampleGroup) end it "metadata `:type => :model` sets up model example groups" do a_model_class = Class.new stub_const "SomeModel", a_model_class group = RSpec.describe(SomeModel, :type => :model) expect(group.new).to be_a(RSpec::Rails::ModelExampleGroup) end it "metadata `:type => :request` sets up request example groups" do a_rails_app = double("Rails application") the_rails_module = Module.new allow(the_rails_module).to receive(:application) { a_rails_app } version = ::Rails::VERSION stub_const "Rails", the_rails_module stub_const 'Rails::VERSION', version group = RSpec.describe("Some Request API", :type => :request) expect(group.new.app).to be(a_rails_app) expect(group.new).to be_a(RSpec::Rails::RequestExampleGroup) end it "metadata `:type => :routing` sets up routing example groups" do a_controller_class = Class.new stub_const "SomeController", a_controller_class group = RSpec.describe(SomeController, :type => :routing) expect(group).to respond_to(:routes) expect(group.new).to be_a(RSpec::Rails::RoutingExampleGroup) end it "metadata `:type => :view` sets up view example groups" do a_helper_module = Module.new stub_const "SomeControllerHelper", a_helper_module group = RSpec.describe("some_controller/action.html.erb", :type => :view) expect(group._default_helper).to be(a_helper_module) expect(group.new).to be_a(RSpec::Rails::ViewExampleGroup) end it "metadata `:type => :feature` sets up feature example groups" do a_rails_app = double("Rails application") the_rails_module = Module.new allow(the_rails_module).to receive(:application) { a_rails_app } version = ::Rails::VERSION stub_const "Rails", the_rails_module stub_const 'Rails::VERSION', version group = RSpec.describe("Some feature description", :type => :feature) example = group.new expect(example).to respond_to(:visit) expect(example).to be_a(RSpec::Rails::FeatureExampleGroup) end if defined?(ActionMailer) it "metadata `:type => :mailer` sets up mailer example groups" do a_mailer_class = Class.new stub_const "SomeMailer", a_mailer_class group = RSpec.describe(SomeMailer, :type => :mailer) expect(group.mailer_class).to be(a_mailer_class) expect(group.new).to be_a(RSpec::Rails::MailerExampleGroup) end end if ::Rails::VERSION::STRING > '5' it "has a default #file_fixture_path of 'spec/fixtures/files'" do expect(config.file_fixture_path).to eq("spec/fixtures/files") end end end rspec-rails-3.7.2/spec/rspec/rails/example/000077500000000000000000000000001320451746500205715ustar00rootroot00000000000000rspec-rails-3.7.2/spec/rspec/rails/example/controller_example_group_spec.rb000066400000000000000000000172031320451746500272450ustar00rootroot00000000000000require "spec_helper" class ::ApplicationController def self.abstract?; false; end end module RSpec::Rails describe ControllerExampleGroup do it_behaves_like "an rspec-rails example group mixin", :controller, './spec/controllers/', '.\\spec\\controllers\\' def group_for(klass) RSpec::Core::ExampleGroup.describe klass do include ControllerExampleGroup end end let(:group) { group_for ApplicationController } it "includes routing matchers" do expect(group.included_modules).to include(RSpec::Rails::Matchers::RoutingMatchers) end context "with implicit subject" do it "uses the controller as the subject" do controller = double('controller') example = group.new allow(example).to receive_messages(:controller => controller) expect(example.subject).to eq(controller) end it "doesn't cause let definition priority to be changed" do # before #738 implicit subject definition for controllers caused # external methods to take precedence over our let definitions with_isolated_config do |config| mod = Module.new do def my_helper "other_value" end end config.include mod group.class_exec do let(:my_helper) { "my_value" } end expect(group.new.my_helper).to eq "my_value" end end end context "with explicit subject" do it "uses the specified subject instead of the controller" do sub_group = group.describe do subject { 'explicit' } end example = sub_group.new expect(example.subject).to eq('explicit') end end describe "#controller" do let(:controller) { double('controller') } let(:example) { group.new } let(:routes) do routes = nil with_isolated_stderr do routes = ActionDispatch::Routing::RouteSet.new routes.draw { resources :foos } end routes end before do group.class_exec do controller(Class.new) { } end allow(controller).to receive(:foos_url).and_return('http://test.host/foos') allow(example).to receive_messages(:controller => controller) example.instance_variable_set(:@orig_routes, routes) end it "delegates named route helpers to the underlying controller" do expect(example.foos_url).to eq('http://test.host/foos') end if Rails.version.to_f >= 4.2 it "calls NamedRouteCollection#route_defined? when it checks that given route is defined or not" do expect(routes.named_routes).to receive(:route_defined?).and_return(true) expect(routes.named_routes).not_to receive(:helpers) example.foos_url end else it "calls NamedRouteCollection#helpers#include? when it checks that given route is defined or not" do expect(routes.named_routes).to \ receive_message_chain(:helpers, :include?).with(:foos_url).and_return(true) example.foos_url end 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 let(:anonymous_klass) { Class.new } let(:group) { group_for(anonymous_klass) } it "defaults to inferring anonymous controller class" do expect(RSpec.configuration.infer_base_class_for_anonymous_controllers).to be_truthy end context "when infer_base_class_for_anonymous_controllers is true" do around(:example) do |ex| with_isolated_config do |config| config.infer_base_class_for_anonymous_controllers = true ex.run end end it "infers the anonymous controller class" do group.controller { } expect(group.controller_class.superclass).to eq(anonymous_klass) end it "infers the anonymous controller class when no ApplicationController is present" do hide_const '::ApplicationController' group.controller { } expect(group.controller_class.superclass).to eq(anonymous_klass) end end context "when infer_base_class_for_anonymous_controllers is false" do around(:example) do |ex| with_isolated_config do |config| config.infer_base_class_for_anonymous_controllers = false ex.run end end it "sets the anonymous controller class to ApplicationController" do group.controller { } expect(group.controller_class.superclass).to eq(ApplicationController) end it "sets the anonymous controller class to ActiveController::Base when no ApplicationController is present" do hide_const '::ApplicationController' group.controller { } expect(group.controller_class.superclass).to eq(ActionController::Base) end end end describe "controller name" do let(:controller_class) { group.controller_class } it "sets the name as AnonymousController if it's anonymous" do group.controller { } expect(controller_class.name).to eq "AnonymousController" end it "sets the name according to defined controller if it is not anonymous" do stub_const "FoosController", Class.new(::ApplicationController) group.controller(FoosController) { } expect(controller_class.name).to eq "FoosController" end it "sets name as AnonymousController if defined as ApplicationController" do group.controller(ApplicationController) { } expect(controller_class.name).to eq "AnonymousController" end it "sets name as AnonymousController if the controller is abstract" do abstract_controller = Class.new(::ApplicationController) def abstract_controller.abstract?; true; end group.controller(abstract_controller) { } expect(controller_class.name).to eq "AnonymousController" end it "sets name as AnonymousController if it inherits outer group's anonymous controller" do outer_group = group_for ApplicationController outer_group.controller { } inner_group = group.describe { } inner_group.controller(outer_group.controller_class) { } expect(inner_group.controller_class.name).to eq "AnonymousController" end end context "in a namespace" do describe "controller name" do let(:controller_class) { group.controller_class } it "sets the name according to the defined controller namespace if it is not anonymous" do stub_const "A::B::FoosController", Class.new(::ApplicationController) group.controller(A::B::FoosController) { } expect(controller_class.name).to eq "A::B::FoosController" end it "sets the name as 'AnonymousController' if the controller is abstract" do abstract_controller = Class.new(::ApplicationController) def abstract_controller.abstract?; true; end stub_const "A::B::FoosController", abstract_controller group.controller(A::B::FoosController) { } expect(controller_class.name).to eq "AnonymousController" end end pending "sets up resourceful routes on the example" end end end rspec-rails-3.7.2/spec/rspec/rails/example/feature_example_group_spec.rb000066400000000000000000000024201320451746500265100ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe FeatureExampleGroup do it_behaves_like "an rspec-rails example group mixin", :feature, './spec/features/', '.\\spec\\features\\' it "includes Rails route helpers" do with_isolated_stderr do Rails.application.routes.draw do get "/foo", :as => :foo, :to => "foo#bar" end 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-3.7.2/spec/rspec/rails/example/helper_example_group_spec.rb000066400000000000000000000044121320451746500263370ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe HelperExampleGroup do module ::FoosHelper class InternalClass end end subject { HelperExampleGroup } it_behaves_like "an rspec-rails example group mixin", :helper, './spec/helpers/', '.\\spec\\helpers\\' it "provides a controller_path based on the helper module's name" do example = double allow(example).to receive_message_chain(:example_group, :described_class) { FoosHelper } helper_spec = Object.new.extend HelperExampleGroup expect(helper_spec.__send__(:_controller_path, example)).to eq("foos") end describe "#helper" do it "returns the instance of AV::Base provided by AV::TC::Behavior" do helper_spec = Object.new.extend HelperExampleGroup expect(helper_spec).to receive(:view_assigns) av_tc_b_view = double('_view') expect(av_tc_b_view).to receive(:assign) allow(helper_spec).to receive(:_view) { av_tc_b_view } expect(helper_spec.helper).to 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 expect(group.new.helper).to be_kind_of(ApplicationHelper) end end end describe HelperExampleGroup::ClassMethods do describe "determine_default_helper_class" do let(:group) do RSpec::Core::ExampleGroup.describe do include HelperExampleGroup end end context "the described is a module" do it "returns the module" do allow(group).to receive(:described_class) { FoosHelper } expect(group.determine_default_helper_class("ignore this")). to eq(FoosHelper) end end context "the described is a class" do it "returns nil" do allow(group).to receive(:described_class) { FoosHelper::InternalClass } expect(group.determine_default_helper_class("ignore this")). to be_nil end end end end end rspec-rails-3.7.2/spec/rspec/rails/example/job_example_group_spec.rb000066400000000000000000000003421320451746500256300ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe JobExampleGroup do if defined?(ActiveJob) it_behaves_like "an rspec-rails example group mixin", :job, './spec/jobs/', '.\\spec\\jobs\\' end end end rspec-rails-3.7.2/spec/rspec/rails/example/mailer_example_group_spec.rb000066400000000000000000000017501320451746500263330ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe MailerExampleGroup do module ::Rails; end before do allow(Rails).to receive_message_chain(:application, :routes, :url_helpers).and_return(Rails) allow(Rails.application).to receive(:config).and_return(double("Rails.application.config").as_null_object) allow(Rails).to receive_message_chain(:configuration, :action_mailer, :default_url_options).and_return({}) end # On 1.9.2, we're getting travis failures from warnings being emitted by these specs # only on 1.9.2 (and only on travis; can't repro locally). The warning is: # /home/travis/.rvm/rubies/ruby-1.9.2-p320/lib/ruby/1.9.1/net/smtp.rb:584: warning: previous definition of tlsconnect was here # For now, we're just going to silence the warning. around { |ex| with_isolated_stderr(&ex) } if RUBY_VERSION == '1.9.2' it_behaves_like "an rspec-rails example group mixin", :mailer, './spec/mailers/', '.\\spec\\mailers\\' end end rspec-rails-3.7.2/spec/rspec/rails/example/model_example_group_spec.rb000066400000000000000000000003031320451746500261530ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe ModelExampleGroup do it_behaves_like "an rspec-rails example group mixin", :model, './spec/models/', '.\\spec\\models\\' end end rspec-rails-3.7.2/spec/rspec/rails/example/request_example_group_spec.rb000066400000000000000000000004511320451746500265470ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe RequestExampleGroup do it_behaves_like "an rspec-rails example group mixin", :request, './spec/requests/', '.\\spec\\requests\\', './spec/integration/', '.\\spec\\integration\\', './spec/api/', '.\\spec\\api\\' end end rspec-rails-3.7.2/spec/rspec/rails/example/routing_example_group_spec.rb000066400000000000000000000013011320451746500265410ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe RoutingExampleGroup do it_behaves_like "an rspec-rails example group mixin", :routing, './spec/routing/', '.\\spec\\routing\\' 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) allow(example).to receive_messages(:routes => routes) expect(example.foo_path).to eq("foo") end end end end rspec-rails-3.7.2/spec/rspec/rails/example/system_example_group_spec.rb000066400000000000000000000004021320451746500263770ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails if ActionPack::VERSION::STRING >= "5.1" RSpec.describe SystemExampleGroup do it_behaves_like "an rspec-rails example group mixin", :system, './spec/system/', '.\\spec\\system\\' end end end rspec-rails-3.7.2/spec/rspec/rails/example/view_example_group_spec.rb000066400000000000000000000171511320451746500260360ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe ViewExampleGroup do it_behaves_like "an rspec-rails example group mixin", :view, './spec/views/', '.\\spec\\views\\' 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' expect(group).to receive(:helper).with(ThingsHelper) group.class_exec 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' expect(group).to receive(:helper).with(Namespaced::ThingsHelper) group.class_exec 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') expect { RSpec::Core::ExampleGroup.describe 'clocks/show.html.erb' do include ViewExampleGroup end }.not_to raise_error end it 'operates normally when the view has no path and there is a Helper class defined' do class ::Helper; end expect { RSpec::Core::ExampleGroup.describe 'show.html.erb' do include ViewExampleGroup end }.not_to 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' expect(group).to receive(:helper).with(ApplicationHelper) group.class_exec 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 defined?(@application_helper) ApplicationHelper = @application_helper end end it 'operates normally' do expect { RSpec::Core::ExampleGroup.describe 'foos/edit.html.erb' do include ViewExampleGroup end }.not_to raise_error end end end describe "routes helpers collides with asset helpers" do let(:view_spec) do Class.new do include ActionView::Helpers::AssetTagHelper include ViewExampleGroup::ExampleMethods end.new end let(:test_routes) do ActionDispatch::Routing::RouteSet.new.tap do |routes| routes.draw { resources :images } end end it "uses routes helpers" do allow(::Rails.application).to receive(:routes).and_return(test_routes) expect(view_spec.image_path(double(:to_param => "42"))). to eq "/images/42" end end describe "#render" do let(:view_spec) do Class.new do local = Module.new do 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 allow(view_spec).to receive(:_default_file_to_render) { "widgets/new" } view_spec.render expect(view_spec.received.first).to eq([{:template => "widgets/new"},{}, nil]) end it "converts the filename components into render options" do allow(view_spec).to receive(:_default_file_to_render) { "widgets/new.en.html.erb" } view_spec.render if ::Rails::VERSION::STRING >= '3.2' expect(view_spec.received.first).to eq([{:template => "widgets/new", :locales=>['en'], :formats=>[:html], :handlers=>['erb']}, {}, nil]) else expect(view_spec.received.first).to eq([{: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') expect(view_spec.received.first).to eq(["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') expect(view_spec.received.first).to eq([{: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 expect(view_spec.controller).to 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 allow(view_spec).to receive(:_default_file_to_render). and_return("things/new.html.erb") expect(view_spec.__send__(:_controller_path)). to eq("things") end end context "with a nested _default_file_to_render" do it "it returns the directory path" do allow(view_spec).to receive(:_default_file_to_render). and_return("admin/things/new.html.erb") expect(view_spec.__send__(:_controller_path)). to eq("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") allow(view_spec).to receive(:_view) { view } expect(view_spec.view).to eq(view) end it 'is accessible to hooks' do with_isolated_config do run_count = 0 RSpec.configuration.before(:each, :type => :view) do allow(view).to receive(:a_stubbed_helper) { :value } run_count += 1 end group = RSpec::Core::ExampleGroup.describe 'a view', :type => :view do specify { true } end group.run NullObject.new expect(run_count).to eq 1 end end end describe "#template" do let(:view_spec) do Class.new do include ViewExampleGroup::ExampleMethods def _view; end end.new end before { allow(RSpec).to receive(:deprecate) } it "is deprecated" do expect(RSpec).to receive(:deprecate) view_spec.template end it "delegates to #view" do expect(view_spec).to receive(:view) view_spec.template end end end end rspec-rails-3.7.2/spec/rspec/rails/fixture_file_upload_support_spec.rb000066400000000000000000000016621320451746500263270ustar00rootroot00000000000000require 'spec_helper' module RSpec::Rails describe FixtureFileUploadSupport do context 'with fixture path set in config' do before { RSpec.configuration.fixture_path = File.dirname(__FILE__) } it 'resolves fixture file' do expect(fixture_file_upload_resolved.run).to be true end end context 'with fixture path set in spec' do it 'resolves fixture file' do expect(fixture_file_upload_resolved(File.dirname(__FILE__)).run).to be true end end def fixture_file_upload_resolved(fixture_path = nil) RSpec::Core::ExampleGroup.describe do include RSpec::Rails::FixtureFileUploadSupport self.fixture_path = fixture_path if fixture_path it 'supports fixture file upload' do file = fixture_file_upload(File.basename(__FILE__)) expect(file.read).to match(/describe FixtureFileUploadSupport/im) end end end end end rspec-rails-3.7.2/spec/rspec/rails/fixture_support_spec.rb000066400000000000000000000007541320451746500237650ustar00rootroot00000000000000require "spec_helper" module RSpec::Rails describe FixtureSupport do context "with use_transactional_fixtures set to false" do it "still supports fixture_path" do allow(RSpec.configuration).to receive(:use_transactional_fixtures) { false } group = RSpec::Core::ExampleGroup.describe do include FixtureSupport end expect(group).to respond_to(:fixture_path) expect(group).to respond_to(:fixture_path=) end end end end rspec-rails-3.7.2/spec/rspec/rails/matchers/000077500000000000000000000000001320451746500207445ustar00rootroot00000000000000rspec-rails-3.7.2/spec/rspec/rails/matchers/active_job_spec.rb000066400000000000000000000213351320451746500244140ustar00rootroot00000000000000require "spec_helper" require "rspec/rails/feature_check" if RSpec::Rails::FeatureCheck.has_active_job? require "rspec/rails/matchers/active_job" class GlobalIdModel include GlobalID::Identification attr_reader :id def self.find(id) new(id) end def initialize(id) @id = id end def ==(comparison_object) id == comparison_object.id end def to_global_id(options = {}) @global_id ||= GlobalID.create(self, :app => "rspec-suite") end end end RSpec.describe "ActiveJob matchers", :skip => !RSpec::Rails::FeatureCheck.has_active_job? do around do |example| original_logger = ActiveJob::Base.logger ActiveJob::Base.logger = Logger.new(nil) # Silence messages "[ActiveJob] Enqueued ...". example.run ActiveJob::Base.logger = original_logger end let(:heavy_lifting_job) do Class.new(ActiveJob::Base) do def perform; end def self.name; "HeavyLiftingJob"; end end end let(:hello_job) do Class.new(ActiveJob::Base) do def perform(*) end def self.name; "HelloJob"; end end end let(:logging_job) do Class.new(ActiveJob::Base) do def perform; end def self.name; "LoggingJob"; end end end before do ActiveJob::Base.queue_adapter = :test end describe "have_enqueued_job" do it "raises ArgumentError when no Proc passed to expect" do expect { expect(heavy_lifting_job.perform_later).to have_enqueued_job }.to raise_error(ArgumentError) end it "passes with default jobs count (exactly one)" do expect { heavy_lifting_job.perform_later }.to have_enqueued_job end it "passes when using alias" do expect { heavy_lifting_job.perform_later }.to enqueue_job end it "counts only jobs enqueued in block" do heavy_lifting_job.perform_later expect { heavy_lifting_job.perform_later }.to have_enqueued_job.exactly(1) end it "passes when negated" do expect { }.not_to have_enqueued_job end it "fails when job is not enqueued" do expect { expect { }.to have_enqueued_job }.to raise_error(/expected to enqueue exactly 1 jobs, but enqueued 0/) end it "fails when too many jobs enqueued" do expect { expect { heavy_lifting_job.perform_later heavy_lifting_job.perform_later }.to have_enqueued_job.exactly(1) }.to raise_error(/expected to enqueue exactly 1 jobs, but enqueued 2/) end it "reports correct number in fail error message" do heavy_lifting_job.perform_later expect { expect { }.to have_enqueued_job.exactly(1) }.to raise_error(/expected to enqueue exactly 1 jobs, but enqueued 0/) end it "fails when negated and job is enqueued" do expect { expect { heavy_lifting_job.perform_later }.not_to have_enqueued_job }.to raise_error(/expected not to enqueue exactly 1 jobs, but enqueued 1/) end it "passes with job name" do expect { hello_job.perform_later heavy_lifting_job.perform_later }.to have_enqueued_job(hello_job).exactly(1).times end it "passes with multiple jobs" do expect { hello_job.perform_later logging_job.perform_later heavy_lifting_job.perform_later }.to have_enqueued_job(hello_job).and have_enqueued_job(logging_job) end it "passes with :once count" do expect { hello_job.perform_later }.to have_enqueued_job.exactly(:once) end it "passes with :twice count" do expect { hello_job.perform_later hello_job.perform_later }.to have_enqueued_job.exactly(:twice) end it "passes with :thrice count" do expect { hello_job.perform_later hello_job.perform_later hello_job.perform_later }.to have_enqueued_job.exactly(:thrice) end it "passes with at_least count when enqueued jobs are over limit" do expect { hello_job.perform_later hello_job.perform_later }.to have_enqueued_job.at_least(:once) end it "passes with at_most count when enqueued jobs are under limit" do expect { hello_job.perform_later }.to have_enqueued_job.at_most(:once) end it "generates failure message with at least hint" do expect { expect { }.to have_enqueued_job.at_least(:once) }.to raise_error(/expected to enqueue at least 1 jobs, but enqueued 0/) end it "generates failure message with at most hint" do expect { expect { hello_job.perform_later hello_job.perform_later }.to have_enqueued_job.at_most(:once) }.to raise_error(/expected to enqueue at most 1 jobs, but enqueued 2/) end it "passes with provided queue name" do expect { hello_job.set(:queue => "low").perform_later }.to have_enqueued_job.on_queue("low") end it "passes with provided at date" do date = Date.tomorrow.noon expect { hello_job.set(:wait_until => date).perform_later }.to have_enqueued_job.at(date) end it "passes with provided arguments" do expect { hello_job.perform_later(42, "David") }.to have_enqueued_job.with(42, "David") end it "passes with provided arguments containing global id object" do global_id_object = GlobalIdModel.new("42") expect { hello_job.perform_later(global_id_object) }.to have_enqueued_job.with(global_id_object) end it "passes with provided argument matchers" do expect { hello_job.perform_later(42, "David") }.to have_enqueued_job.with(42, "David") end it "generates failure message with all provided options" do date = Date.tomorrow.noon message = "expected to enqueue exactly 2 jobs, with [42], on queue low, at #{date}, but enqueued 0" + \ "\nQueued jobs:" + \ "\n HelloJob job with [1], on queue default" expect { expect { hello_job.perform_later(1) }.to have_enqueued_job(hello_job).with(42).on_queue("low").at(date).exactly(2).times }.to raise_error(message) end it "throws descriptive error when no test adapter set" do queue_adapter = ActiveJob::Base.queue_adapter ActiveJob::Base.queue_adapter = :inline expect { expect { heavy_lifting_job.perform_later }.to have_enqueued_job }.to raise_error("To use ActiveJob matchers set `ActiveJob::Base.queue_adapter = :test`") ActiveJob::Base.queue_adapter = queue_adapter end it "fails with with block with incorrect data" do expect { expect { hello_job.perform_later("asdf") }.to have_enqueued_job(hello_job).with { |arg| expect(arg).to eq("zxcv") } }.to raise_error { |e| expect(e.message).to match(/expected: "zxcv"/) expect(e.message).to match(/got: "asdf"/) } end it "passes multiple arguments to with block" do expect { hello_job.perform_later("asdf", "zxcv") }.to have_enqueued_job(hello_job).with { |first_arg, second_arg| expect(first_arg).to eq("asdf") expect(second_arg).to eq("zxcv") } end it "passess deserialized arguments to with block" do global_id_object = GlobalIdModel.new("42") expect { hello_job.perform_later(global_id_object, :symbolized_key => "asdf") }.to have_enqueued_job(hello_job).with { |first_arg, second_arg| expect(first_arg).to eq(global_id_object) expect(second_arg).to eq({:symbolized_key => "asdf"}) } end it "only calls with block if other conditions are met" do noon = Date.tomorrow.noon midnight = Date.tomorrow.midnight expect { hello_job.set(:wait_until => noon).perform_later("asdf") hello_job.set(:wait_until => midnight).perform_later("zxcv") }.to have_enqueued_job(hello_job).at(noon).with { |arg| expect(arg).to eq("asdf") } end end describe "have_been_enqueued" do before { ActiveJob::Base.queue_adapter.enqueued_jobs.clear } it "passes with default jobs count (exactly one)" do heavy_lifting_job.perform_later expect(heavy_lifting_job).to have_been_enqueued end it "counts all enqueued jobs" do heavy_lifting_job.perform_later heavy_lifting_job.perform_later expect(heavy_lifting_job).to have_been_enqueued.exactly(2) end it "passes when negated" do expect(heavy_lifting_job).not_to have_been_enqueued end it "fails when job is not enqueued" do expect { expect(heavy_lifting_job).to have_been_enqueued }.to raise_error(/expected to enqueue exactly 1 jobs, but enqueued 0/) end end end rspec-rails-3.7.2/spec/rspec/rails/matchers/be_a_new_spec.rb000066400000000000000000000126751320451746500240550ustar00rootroot00000000000000require "spec_helper" describe "be_a_new matcher" do 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 expect(record).to be_a_new(record.class) end end context "wrong class" do it "fails" do expect(record).not_to 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 expect(record).not_to be_a_new(record.class) end end context "wrong class" do it "fails" do expect(record).not_to 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 expect(record).to be_a_new(record.class).with(:foo => 'foo', :bar => 'bar') end end context "one attribute same" do it "passes" do expect(record).to be_a_new(record.class).with(:foo => 'foo') end end context "with composable matchers" do context "one attribute is a composable matcher" do it "passes" do expect(record).to be_a_new(record.class).with( :foo => a_string_including("foo")) end it "fails" do expect { expect(record).to be_a_new(record.class).with( :foo => a_string_matching("bar")) }.to raise_error("attribute {\"foo\"=>(a string matching \"bar\")} was not set on #{record.inspect}") end context "matcher is wrong type" do it "fails" do expect { expect(record).to be_a_new(record.class).with( :foo => a_hash_including({:no_foo => "foo"})) }.to raise_error {|e| expect(e.message).to eq("no implicit conversion of Hash into String").or eq("can't convert Hash into String") } end end end context "two attributes are composable matchers" do context "both matchers present in actual" do it "passes" do expect(record).to be_a_new(record.class).with( :foo => a_string_matching("foo"), :bar => a_string_matching("bar") ) end end context "only one matcher present in actual" do it "fails" do expect { expect(record).to be_a_new(record.class).with( :foo => a_string_matching("foo"), :bar => a_string_matching("barn") ) }.to raise_error("attribute {\"bar\"=>(a string matching \"barn\")} was not set on #{record.inspect}") end end end end context "no attributes same" do it "fails" do expect { expect(record).to be_a_new(record.class).with(:zoo => 'zoo', :car => 'car') }.to raise_error {|e| expect(e.message).to match(/attributes \{.*\} were not set on #{Regexp.escape record.inspect}/) expect(e.message).to match(/"zoo"=>"zoo"/) expect(e.message).to match(/"car"=>"car"/) } end end context "one attribute value not the same" do it "fails" do expect { expect(record).to 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 { expect(record).to 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 { expect(record).to be_a_new(String).with(:zoo => 'zoo', :car => 'car') }.to raise_error {|e| expect(e.message).to match(/expected #{Regexp.escape record.inspect} to be a new String and attributes \{.*\} were not set on #{Regexp.escape record.inspect}/) expect(e.message).to match(/"zoo"=>"zoo"/) expect(e.message).to match(/"car"=>"car"/) } end end context "one attribute value not the same" do it "fails" do expect { expect(record).to 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-3.7.2/spec/rspec/rails/matchers/be_new_record_spec.rb000066400000000000000000000014021320451746500250750ustar00rootroot00000000000000require "spec_helper" describe "be_new_record" do context "a new record" do let(:record) { double('record', :new_record? => true) } it "passes" do expect(record).to 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 "a persisted record" do let(:record) { double('record', :new_record? => false) } it "fails" do expect(record).not_to 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-3.7.2/spec/rspec/rails/matchers/be_routable_spec.rb000066400000000000000000000026351320451746500245740ustar00rootroot00000000000000require "spec_helper" describe "be_routable" do include RSpec::Rails::Matchers::RoutingMatchers attr_reader :routes before { @routes = double("routes") } it "provides a description" do expect(be_routable.description).to eq("be routable") end context "with should" do it "passes if routes recognize the path" do allow(routes).to receive(:recognize_path) { {} } expect do expect({:get => "/a/path"}).to be_routable end.to_not raise_error end it "fails if routes do not recognize the path" do allow(routes).to receive(:recognize_path) { raise ActionController::RoutingError.new('ignore') } expect do expect({:get => "/a/path"}).to 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 allow(routes).to receive(:recognize_path) { raise ActionController::RoutingError.new('ignore') } expect do expect({:get => "/a/path"}).not_to be_routable end.to_not raise_error end it "fails if routes recognize the path" do allow(routes).to receive(:recognize_path) { {:controller => "foo"} } expect do expect({:get => "/a/path"}).not_to 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-3.7.2/spec/rspec/rails/matchers/be_valid_spec.rb000066400000000000000000000032751320451746500240570ustar00rootroot00000000000000require "spec_helper" require 'rspec/rails/matchers/be_valid' describe "be_valid matcher" do class Post include ActiveModel::Validations attr_accessor :title validates_presence_of :title end class Book def valid? false end def errors ['the spine is broken', 'the pages are dog-eared'] end end class Boat def valid? false end end let(:post) { Post.new } let(:book) { Book.new } let(:boat) { Boat.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 the error messages for simple implementations of error messages" do expect { expect(book).to be_valid }.to raise_exception(/the spine is broken/) end it "includes a brief error message for the simplest implementation of validity" do expect { expect(boat).to be_valid }.to raise_exception(/expected .+ to be valid\z/) end it "includes a failure message for the negative case" do allow(post).to receive(: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 expect(post).to receive(:valid?).with(:create) { true } expect(post).to be_valid(:create) end it "does not include the validation context if not provided" do expect(post).to receive(:valid?).with(no_args) { true } expect(post).to be_valid end end rspec-rails-3.7.2/spec/rspec/rails/matchers/has_spec.rb000066400000000000000000000012561320451746500230620ustar00rootroot00000000000000require '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 expect(owner.associated_items).to have_some_quality end end rspec-rails-3.7.2/spec/rspec/rails/matchers/have_http_status_spec.rb000066400000000000000000000365711320451746500257040ustar00rootroot00000000000000require 'spec_helper' RSpec.describe "have_http_status" do def create_response(opts = {}) ActionDispatch::TestResponse.new(opts.fetch(:status)).tap {|x| x.request = ActionDispatch::Request.new({}) } end shared_examples_for "supports different response instances" do context "given an ActionDispatch::Response" do it "returns true for a response with the same code" do response = ::ActionDispatch::Response.new(code).tap {|x| x.request = ActionDispatch::Request.new({}) } expect( matcher.matches?(response) ).to be(true) end end context "given an ActionDispatch::TestResponse" do it "returns true for a response with the same code" do response = ::ActionDispatch::TestResponse.new(code).tap {|x| x.request = ActionDispatch::Request.new({}) } expect( matcher.matches?(response) ).to be(true) end end context "given something that acts as a Capybara::Session" do it "returns true for a response with the same code" do response = instance_double( '::Capybara::Session', :status_code => code, :response_headers => {}, :body => "" ) expect( matcher.matches?(response) ).to be(true) end end it "returns false given another type" do response = Object.new expect( matcher.matches?(response) ).to be(false) end it "has a failure message reporting it was given another type" do response = Object.new expect{ matcher.matches?(response) }. to change(matcher, :failure_message). to("expected a response object, but an instance of Object was received") end it "has a negated failure message reporting it was given another type" do response = Object.new expect{ matcher.matches?(response) }. to change(matcher, :failure_message_when_negated). to("expected a response object, but an instance of Object was received") end end context "with a numeric status code" do it_behaves_like "supports different response instances" do subject(:matcher) { have_http_status(code) } let(:code) { 209 } end describe "matching a response" do it "returns true for a response with the same code" do any_numeric_code = 209 have_numeric_code = have_http_status(any_numeric_code) response = create_response(:status => any_numeric_code) expect( have_numeric_code.matches?(response) ).to be(true) end it "returns false for a response with a different code" do any_numeric_code = 209 have_numeric_code = have_http_status(any_numeric_code) response = create_response(:status => any_numeric_code + 1) expect( have_numeric_code.matches?(response) ).to be(false) end end it "describes responding with the numeric status code" do any_numeric_code = 209 have_numeric_code = have_http_status(any_numeric_code) expect(have_numeric_code.description). to eq("respond with numeric status code 209") end it "has a failure message reporting the expected and actual status codes" do any_numeric_code = 209 have_numeric_code = have_http_status(any_numeric_code) response = create_response(:status => any_numeric_code + 1) expect{ have_numeric_code.matches? response }. to change(have_numeric_code, :failure_message). to("expected the response to have status code 209 but it was 210") end it "has a negated failure message reporting the expected status code" do any_numeric_code = 209 have_numeric_code = have_http_status(any_numeric_code) expect( have_numeric_code.failure_message_when_negated ). to eq("expected the response not to have status code 209 but it did") end end context "with a symbolic status" do # :created => 201 status code # see http://guides.rubyonrails.org/layouts_and_rendering.html#the-status-option let(:created_code) { 201 } let(:created_symbolic_status) { :created } it_behaves_like "supports different response instances" do subject(:matcher) { have_http_status(created_symbolic_status) } let(:code) { created_code } end describe "matching a response" do it "returns true for a response with the equivalent code" do any_symbolic_status = created_symbolic_status have_symbolic_status = have_http_status(any_symbolic_status) response = create_response(:status => created_code) expect( have_symbolic_status.matches?(response) ).to be(true) end it "returns false for a response with a different code" do any_symbolic_status = created_symbolic_status have_symbolic_status = have_http_status(any_symbolic_status) response = create_response(:status => created_code + 1) expect( have_symbolic_status.matches?(response) ).to be(false) end end it "describes responding by the symbolic and associated numeric status code" do any_symbolic_status = created_symbolic_status have_symbolic_status = have_http_status(any_symbolic_status) expect(have_symbolic_status.description). to eq("respond with status code :created (201)") end it "has a failure message reporting the expected and actual statuses" do any_symbolic_status = created_symbolic_status have_symbolic_status = have_http_status(any_symbolic_status) response = create_response(:status => created_code + 1) expect{ have_symbolic_status.matches? response }. to change(have_symbolic_status, :failure_message). to("expected the response to have status code :created (201) but it was :accepted (202)") end it "has a negated failure message reporting the expected status code" do any_symbolic_status = created_symbolic_status have_symbolic_status = have_http_status(any_symbolic_status) expect( have_symbolic_status.failure_message_when_negated ). to eq("expected the response not to have status code :created (201) but it did") end it "raises an ArgumentError" do expect{ have_http_status(:not_a_status) }.to raise_error ArgumentError end end context "with general status code group", ":error" do # The error query is an alias for `server_error?`: # # - https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/testing/test_response.rb#L27 # - https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/test_response.rb # # `server_error?` is part of the Rack Helpers and is defined as: # # status >= 500 && status < 600 # # See: # # - https://github.com/rack/rack/blob/ce4a3959/lib/rack/response.rb#L122 # - https://github.com/rack/rack/blob/master/lib/rack/response.rb subject(:have_error_status) { have_http_status(:error) } it_behaves_like "supports different response instances" do subject(:matcher) { have_error_status } let(:code) { 555 } end describe "matching a response" do it "returns true for a response with a 5xx status code" do any_5xx_code = 555 response = create_response(:status => any_5xx_code) expect( have_error_status.matches?(response) ).to be(true) end it "returns false for a response with a different code" do client_error_code = 400 response = create_response(:status => client_error_code) expect( have_error_status.matches?(response) ).to be(false) end end it "describes responding with an error status code" do expect(have_error_status.description). to eq("respond with an error status code (5xx)") end it "has a failure message reporting the expected and actual status codes" do client_error_code = 400 response = create_response(:status => client_error_code) expect{ have_error_status.matches? response }. to change(have_error_status, :failure_message). to(/an error status code \(5xx\) but it was 400/) end it "has a negated failure message reporting the expected and actual status codes" do any_5xx_code = 555 response = create_response(:status => any_5xx_code) expect{ have_error_status.matches? response }. to change(have_error_status, :failure_message_when_negated). to(/not to have an error status code \(5xx\) but it was 555/) end end context "with general status code group", ":success" do # The success query is an alias for `successful?`: # # - https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/testing/test_response.rb#L18 # - https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/test_response.rb # # `successful?` is part of the Rack Helpers and is defined as: # # status >= 200 && status < 300 # # See: # # - https://github.com/rack/rack/blob/ce4a3959/lib/rack/response.rb#L119 # - https://github.com/rack/rack/blob/master/lib/rack/response.rb subject(:have_success_status) { have_http_status(:success) } it_behaves_like "supports different response instances" do subject(:matcher) { have_success_status } let(:code) { 222 } end describe "matching a response" do it "returns true for a response with a 2xx status code" do any_2xx_code = 222 response = create_response(:status => any_2xx_code) expect( have_success_status.matches?(response) ).to be(true) end it "returns false for a response with a different code" do non_success_code = 400 response = create_response(:status => non_success_code) expect( have_success_status.matches?(response) ).to be(false) end end it "describes responding with a success status code" do expect(have_success_status.description). to eq("respond with a success status code (2xx)") end it "has a failure message reporting the expected and actual status codes" do non_success_code = 400 response = create_response(:status => non_success_code) expect{ have_success_status.matches? response }. to change(have_success_status, :failure_message). to(/a success status code \(2xx\) but it was 400/) end it "has a negated failure message reporting the expected and actual status codes" do any_2xx_code = 222 response = create_response(:status => any_2xx_code) expect{ have_success_status.matches? response }. to change(have_success_status, :failure_message_when_negated). to(/not to have a success status code \(2xx\) but it was 222/) end end context "with general status code group", ":missing" do # The missing query is an alias for `not_found?`: # # - https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/testing/test_response.rb#L21 # - https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/test_response.rb # # `not_found?` is part of the Rack Helpers and is defined as: # # status == 404 # # See: # # - https://github.com/rack/rack/blob/ce4a3959/lib/rack/response.rb#L130 # - https://github.com/rack/rack/blob/master/lib/rack/response.rb subject(:have_missing_status) { have_http_status(:missing) } it_behaves_like "supports different response instances" do subject(:matcher) { have_missing_status } let(:code) { 404 } end describe "matching a response" do it "returns true for a response with a 404 status code" do not_found_status = 404 response = create_response(:status => not_found_status) expect( have_missing_status.matches?(response) ).to be(true) end it "returns false for a response with a different code" do non_missing_status = 400 response = create_response(:status => non_missing_status) expect( have_missing_status.matches?(response) ).to be(false) end end it "describes responding with a missing status code" do expect(have_missing_status.description). to eq("respond with a missing status code (404)") end it "has a failure message reporting the expected and actual status codes" do non_missing_status = 400 response = create_response(:status => non_missing_status) expect{ have_missing_status.matches? response }. to change(have_missing_status, :failure_message). to(/a missing status code \(404\) but it was 400/) end it "has a negated failure message reporting the expected status code" do not_found_status = 404 response = create_response(:status => not_found_status) expect{ have_missing_status.matches? response }. to change(have_missing_status, :failure_message_when_negated). to(/not to have a missing status code \(404\) but it was 404/) end end context "with general status code group", ":redirect" do # The redirect query is an alias for `redirection?`: # # - https://github.com/rails/rails/blob/ca200378/actionpack/lib/action_dispatch/testing/test_response.rb#L24 # - https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/test_response.rb # # `redirection?` is part of the Rack Helpers and is defined as: # # status >= 300 && status < 400 # # See: # # - https://github.com/rack/rack/blob/ce4a3959/lib/rack/response.rb#L120 # - https://github.com/rack/rack/blob/master/lib/rack/response.rb subject(:have_redirect_status) { have_http_status(:redirect) } it_behaves_like "supports different response instances" do subject(:matcher) { have_redirect_status } let(:code) { 308 } end describe "matching a response" do it "returns true for a response with a 3xx status code" do any_3xx_code = 308 response = create_response(:status => any_3xx_code) expect( have_redirect_status.matches?(response) ).to be(true) end it "returns false for a response with a different code" do non_redirect_code = 400 response = create_response(:status => non_redirect_code) expect( have_redirect_status.matches?(response) ).to be(false) end end it "describes responding with a redirect status code" do expect(have_redirect_status.description). to eq("respond with a redirect status code (3xx)") end it "has a failure message reporting the expected and actual status codes" do non_redirect_code = 400 response = create_response(:status => non_redirect_code) expect{ have_redirect_status.matches? response }. to change(have_redirect_status, :failure_message). to(/a redirect status code \(3xx\) but it was 400/) end it "has a negated failure message reporting the expected and actual status codes" do any_3xx_code = 308 response = create_response(:status => any_3xx_code) expect{ have_redirect_status.matches? response }. to change(have_redirect_status, :failure_message_when_negated). to(/not to have a redirect status code \(3xx\) but it was 308/) end end context "with a nil status" do it "raises an ArgumentError" do expect{ have_http_status(nil) }.to raise_error ArgumentError end end end rspec-rails-3.7.2/spec/rspec/rails/matchers/have_rendered_spec.rb000066400000000000000000000106061320451746500251010ustar00rootroot00000000000000require "spec_helper" %w[have_rendered render_template].each do |template_expectation| describe template_expectation do include RSpec::Rails::Matchers::RenderTemplate let(:response) { ActionDispatch::TestResponse.new } context "given a hash" do it "delegates to assert_template" do expect(self).to 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 expect(self).to 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 expect(self).to 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 context "when fails with a redirect" do let(:response) { ActionDispatch::TestResponse.new(303) } def assert_template(*) message = "expecting <'template_name'> but rendering with <[]>" raise ActiveSupport::TestCase::Assertion.new(message) end def normalize_argument_to_redirection(response_redirect_location) "http://test.host/widgets/1" end it "gives informative error message" do response = ActionDispatch::TestResponse.new(302) response.location = "http://test.host/widgets/1" expect do expect(response).to send(template_expectation, "template_name") end.to raise_exception("expecting <'template_name'> but was a redirect to ") end context 'with a badly formatted error message' do def assert_template(*) message = 'expected [] to include "some/path"' raise ActiveSupport::TestCase::Assertion.new(message) end it 'falls back to something informative' do expect do expect(response).to send(template_expectation, "template_name") end.to raise_exception('expected [] to include "some/path" but was a redirect to ') end end end end end end rspec-rails-3.7.2/spec/rspec/rails/matchers/redirect_to_spec.rb000066400000000000000000000041021320451746500246030ustar00rootroot00000000000000require "spec_helper" require "active_support" require "active_support/test_case" describe "redirect_to" do include RSpec::Rails::Matchers::RedirectTo let(:response) { ActionDispatch::TestResponse.new } context "with should" do context "when assert_redirected_to passes" do def assert_redirected_to(*); end it "passes" do expect do expect(response).to 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 expect(response).to 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 expect(response).to 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 expect(response).not_to 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 expect(response).not_to 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 expect(response).not_to redirect_to("destination") end.to raise_exception("oops") end end end end rspec-rails-3.7.2/spec/rspec/rails/matchers/relation_match_array_spec.rb000066400000000000000000000021531320451746500264730ustar00rootroot00000000000000require "spec_helper" describe "ActiveSupport::Relation match_array 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 expect(MockableModel.all).to match_array(models.reverse) end it "fails if the scope encompasses more records than on the right hand side" do MockableModel.create expect(MockableModel.all).not_to match_array(models.reverse) end else it "verifies that the scope returns the records on the right hand side, regardless of order" do expect(MockableModel.scoped).to match_array(models.reverse) end it "fails if the scope encompasses more records than on the right hand side" do MockableModel.create expect(MockableModel.scoped).not_to match_array(models.reverse) end end it "fails if the scope encompasses fewer records than on the right hand side" do expect(MockableModel.limit(models.length - 1)).not_to match_array(models.reverse) end end rspec-rails-3.7.2/spec/rspec/rails/matchers/route_to_spec.rb000066400000000000000000000126341320451746500241510ustar00rootroot00000000000000require "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") expect(matcher.description).to eq("route {:get=>\"path\"} to {\"these\"=>\"options\"}") end it "delegates to assert_recognizes" do expect(self).to receive(:assert_recognizes).with({ "these" => "options" }, { :method=> :get, :path=>"path" }, {}) expect({:get => "path"}).to route_to("these" => "options") end context "with shortcut syntax" do it "routes with extra options" do expect(self).to receive(:assert_recognizes).with({ :controller => "controller", :action => "action", :extra => "options"}, { :method=> :get, :path=>"path" }, {}) expect(get("path")).to route_to("controller#action", :extra => "options") end it "routes without extra options" do expect(self).to receive(:assert_recognizes).with( {:controller => "controller", :action => "action"}, {:method=> :get, :path=>"path" }, {} ) expect(get("path")).to route_to("controller#action") end it "routes with one query parameter" do expect(self).to receive(:assert_recognizes).with( {:controller => "controller", :action => "action", :queryitem => "queryvalue"}, {:method=> :get, :path=>"path" }, {'queryitem' => 'queryvalue' } ) expect(get("path?queryitem=queryvalue")).to route_to("controller#action", :queryitem => 'queryvalue') end it "routes with multiple query parameters" do expect(self).to receive(:assert_recognizes).with( {:controller => "controller", :action => "action", :queryitem => "queryvalue", :qi2 => 'qv2'}, {:method=> :get, :path=>"path"}, {'queryitem' => 'queryvalue', 'qi2' => 'qv2'} ) expect(get("path?queryitem=queryvalue&qi2=qv2")).to route_to("controller#action", :queryitem => 'queryvalue', :qi2 => 'qv2') end it "routes with nested query parameters" do expect(self).to receive(:assert_recognizes).with( {:controller => "controller", :action => "action", 'queryitem' => {'qi2' => 'qv2'}}, {:method=> :get, :path=>"path"}, {'queryitem' => {'qi2' => 'qv2'} } ) expect(get("path?queryitem[qi2]=qv2")).to route_to("controller#action", 'queryitem' => { 'qi2' => 'qv2' }) end end context "with should" do context "when assert_recognizes passes" do it "passes" do expect do expect({:get => "path"}).to 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 expect({:get => "path"}).to 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 expect({:get => "path"}).to 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 expect({:get => "path"}).to 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{ expect({:get => "path"}).not_to route_to("these" => "options") }.to raise_error(/expected \{:get=>"path"\} not to route to \{"these"=>"options"\}/) 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 expect({:get => "path"}).not_to 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 expect({:get => "path"}).not_to 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 expect({:get => "path"}).not_to 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 expect({"this" => "path"}).to route_to("these" => "options") end.to raise_error("this message") end end rspec-rails-3.7.2/spec/rspec/rails/minitest_lifecycle_adapter_spec.rb000066400000000000000000000020431320451746500260470ustar00rootroot00000000000000require "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_group.example("foo") { invocations << :example } example_group.run(NullObject.new) expect(invocations).to eq([ :before_setup, :after_setup, :example, :before_teardown, :after_teardown ]) end it "allows let variables named 'send'" do run_result = ::RSpec::Core::ExampleGroup.describe do let(:send) { "WHAT" } specify { expect(send).to eq "WHAT" } end.run NullObject.new expect(run_result).to be true end end rspec-rails-3.7.2/spec/rspec/rails/setup_and_teardown_adapter_spec.rb000066400000000000000000000035401320451746500260640ustar00rootroot00000000000000require '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 expect(klass).to receive(:before).ordered { |&block| expect(block.call).to eq "foo" } expect(klass).to receive(:before).ordered { |&block| expect(block.call).to eq "bar" } expect(klass).to receive(:before).ordered { |&block| expect(block.call).to eq "baz" } klass.setup :foo klass.setup :bar klass.setup { "baz" } 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 expect(klass).to receive(:prepend_before) { |&block| expect(block.call).to eq "setup fixtures" } expect(klass).to receive(:prepend_before) { |&block| expect(block.call).to eq "setup controller" } klass.setup :setup_fixtures klass.setup :setup_controller_request_and_response end it "registers teardown 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 expect(klass).to receive(:after).ordered { |&block| expect(block.call).to eq "foo" } expect(klass).to receive(:after).ordered { |&block| expect(block.call).to eq "bar" } expect(klass).to receive(:after).ordered { |&block| expect(block.call).to eq "baz" } klass.teardown :foo klass.teardown :bar klass.teardown { "baz" } end end end rspec-rails-3.7.2/spec/rspec/rails/view_rendering_spec.rb000066400000000000000000000106601320451746500235070ustar00rootroot00000000000000require "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 expect(group.new.render_views?).to be_falsey end it "does not render views in a nested group" do expect(group.describe{}.new.render_views?).to be_falsey end end context "ActionController::Metal" do it "renders views" do group.new.tap do |example| def example.controller ActionController::Metal.new end expect(example.render_views?).to be_truthy end end end end describe "#render_views" do context "with no args" do it "tells examples to render views" do group.render_views expect(group.new.render_views?).to be_truthy end end context "with true" do it "tells examples to render views" do group.render_views true expect(group.new.render_views?).to be_truthy end end context "with false" do it "tells examples not to render views" do group.render_views false expect(group.new.render_views?).to be_falsey end it "overrides the global config if render_views is enabled there" do allow(RSpec.configuration).to receive(:render_views?).and_return true group.render_views false expect(group.new.render_views?).to be_falsey end end it 'propogates to examples in nested groups properly' do value = :unset group.class_exec do render_views describe "nested" do it { value = render_views? } end end.run(double.as_null_object) expect(value).to eq(true) 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 expect(nested_group.new.render_views?).to be_truthy end end context "with true" do it "tells examples to render views" do nested_group.render_views true expect(nested_group.new.render_views?).to be_truthy end end context "with false" do it "tells examples not to render views" do nested_group.render_views false expect(nested_group.new.render_views?).to be_falsey end end it "leaves the parent group as/is" do group.render_views nested_group.render_views false expect(group.new.render_views?).to be_truthy end it "overrides the value inherited from the parent group" do group.render_views nested_group.render_views false expect(nested_group.new.render_views?).to be_falsey end it "passes override to children" do group.render_views nested_group.render_views false expect(nested_group.describe{}.new.render_views?).to be_falsey end end end context 'when render_views? is false' do let(:controller) { ActionController::Base.new } before { controller.extend(ViewRendering::EmptyTemplates) } it 'supports manipulating view paths' do controller.prepend_view_path 'app/views' controller.append_view_path 'app/others' expect(controller.view_paths.map(&:to_s)).to match_paths 'app/views', 'app/others' end it 'supports manipulating view paths with arrays' do controller.prepend_view_path ['app/views', 'app/legacy_views'] controller.append_view_path ['app/others', 'app/more_views'] expect(controller.view_paths.map(&:to_s)).to match_paths 'app/views', 'app/legacy_views', 'app/others', 'app/more_views' end it 'supports manipulating view paths with resolvers' do expect { controller.prepend_view_path ActionView::Resolver.new controller.append_view_path ActionView::Resolver.new }.to_not raise_error end def match_paths(*paths) eq paths.map { |path| File.expand_path path } end end end end rspec-rails-3.7.2/spec/rspec/rails/view_spec_methods_spec.rb000066400000000000000000000041451320451746500242100ustar00rootroot00000000000000module RSpec::Rails RSpec.describe ViewSpecMethods do before do class ::VCSampleClass; end end after do Object.send(:remove_const, :VCSampleClass) end describe ".add_extra_params_accessors_to" do describe "when accessors are not yet defined" do it "adds them as instance methods" do ViewSpecMethods.add_to(VCSampleClass) expect(VCSampleClass.instance_methods.map(&:to_sym)).to(include(:extra_params=)) expect(VCSampleClass.instance_methods.map(&:to_sym)).to(include(:extra_params)) end describe "the added #extra_params reader" do it "raises an error when a user tries to mutate it" do ViewSpecMethods.add_to(VCSampleClass) expect { VCSampleClass.new.extra_params[:id] = 4 }.to raise_error(/can't modify frozen/) end end end describe "when accessors are already defined" do before do class ::VCSampleClass def extra_params; end def extra_params=; end end end it "does not redefine them" do ViewSpecMethods.add_to(VCSampleClass) expect(VCSampleClass.new.extra_params).to be_nil end end end describe ".remove_extra_params_accessors_from" do describe "when accessors are defined" do before do ViewSpecMethods.add_to(VCSampleClass) end it "removes them" do ViewSpecMethods.remove_from(VCSampleClass) expect(VCSampleClass.instance_methods).to_not include("extra_params=") expect(VCSampleClass.instance_methods).to_not include(:extra_params=) expect(VCSampleClass.instance_methods).to_not include("extra_params") expect(VCSampleClass.instance_methods).to_not include(:extra_params) end end describe "when accessors are not defined" do it "does nothing" do expect { ViewSpecMethods.remove_from(VCSampleClass) }.to_not change { VCSampleClass.instance_methods } end end end end end rspec-rails-3.7.2/spec/rspec/rails_spec.rb000066400000000000000000000013351320451746500204770ustar00rootroot00000000000000require 'rspec/support/spec/library_wide_checks' RSpec.describe "RSpec::Rails" do include RSpec::Support::WhitespaceChecks # Pasted from rspec-support lib/rspec/support/spec/library_wide_checks.rb:134 # Easier to do that here than to extract it out RSpec::Matchers.define :be_well_formed do match do |actual| actual.empty? end failure_message do |actual| actual.join("\n") end end it "has no malformed whitespace", :slow do error_messages = [] `git ls-files -z`.split("\x0").each do |filename| error_messages << check_for_tab_characters(filename) error_messages << check_for_extra_spaces(filename) end expect(error_messages.compact).to be_well_formed end end rspec-rails-3.7.2/spec/sanity_check_spec.rb000066400000000000000000000024371320451746500207210ustar00rootroot00000000000000require 'spec_helper' require 'pathname' RSpec.describe "Verify required rspec dependencies" do tmp_root = Pathname.new(RSpec::Core::RubyProject.root).join("tmp") before{ FileUtils.mkdir_p tmp_root } it "fails when libraries are not required" do script = tmp_root.join("fail_sanity_check") File.open(script, "w") do |f| f.write <<-EOF.gsub(/^\s+\|/, '') |#!/usr/bin/env ruby |RSpec::Support.require_rspec_core "project_initializer" EOF end FileUtils.chmod 0777, script Bundler.with_clean_env do expect(`bundle exec #{script} 2>&1`). to match(/uninitialized constant RSpec::Support/). or match(/undefined method `require_rspec_core' for RSpec::Support:Module/) expect($?.exitstatus).to eq(1) end end it "passes when libraries are required" do script = tmp_root.join("pass_sanity_check") File.open(script, "w") do |f| f.write <<-EOF.gsub(/^\s+\|/, '') |#!/usr/bin/env ruby |require 'rspec/core' |require 'rspec/support' |RSpec::Support.require_rspec_core "project_initializer" EOF end FileUtils.chmod 0777, script Bundler.with_clean_env do expect(`bundle exec #{script} 2>&1`).to be_empty expect($?.exitstatus).to eq(0) end end end rspec-rails-3.7.2/spec/spec_helper.rb000066400000000000000000000016341320451746500175320ustar00rootroot00000000000000require 'rails/all' module RSpecRails class Application < ::Rails::Application self.config.secret_key_base = 'ASecretString' if config.respond_to? :secret_key_base end end I18n.enforce_available_locales = true if I18n.respond_to?(:enforce_available_locales) require 'rspec/support/spec' 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.filter_run :focus config.run_all_when_everything_filtered = true config.order = :random real_world = nil 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 end rspec-rails-3.7.2/spec/support/000077500000000000000000000000001320451746500164245ustar00rootroot00000000000000rspec-rails-3.7.2/spec/support/ar_classes.rb000066400000000000000000000017111320451746500210700ustar00rootroot00000000000000ActiveRecord::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 host.reset_column_information 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-3.7.2/spec/support/generators.rb000066400000000000000000000041761320451746500211320ustar00rootroot00000000000000module RSpec module Rails module Specs module Generators module Macros # Tell the generator where to put its output (what it thinks of as # Rails.root) def set_default_destination destination File.expand_path("../../../tmp", __FILE__) end def setup_default_destination set_default_destination before { prepare_destination } end end def self.included(klass) klass.extend(Macros) end shared_examples_for "a request spec generator" do describe 'generated with flag `--no-request-specs`' do before do run_generator %w(posts --no-request-specs) end subject(:request_spec) { file('spec/requests/posts_spec.rb') } it "does not create the request spec" do expect(request_spec).not_to exist end end describe 'generated with no flags' do before do run_generator %w(posts) end subject(:request_spec) { file('spec/requests/posts_spec.rb') } it "creates the request spec" do expect(request_spec).to exist end it "the generator requires 'rails_helper'" do expect(request_spec).to contain(/require 'rails_helper'/) end it "the generator describes the provided NAME without monkey " \ "patching setting the type to `:request`" do expect(request_spec).to contain( /^RSpec.describe \"Posts\", #{type_metatag(:request)}/ ) end it "the generator includes a sample GET request" do expect(request_spec).to contain(/describe "GET \/posts"/) end it "the generator sends the GET request to the index path" do expect(request_spec).to contain(/get posts_index_path/) end end end end end end end RSpec.configure do |config| config.include RSpec::Rails::Specs::Generators, :type => :generator end rspec-rails-3.7.2/spec/support/helpers.rb000066400000000000000000000005651320451746500204210ustar00rootroot00000000000000module Helpers include RSpec::Rails::FeatureCheck def with_isolated_config original_config = RSpec.configuration RSpec.configuration = RSpec::Core::Configuration.new RSpec::Rails.initialize_configuration(RSpec.configuration) yield RSpec.configuration ensure RSpec.configuration = original_config end RSpec.configure {|c| c.include self} end rspec-rails-3.7.2/spec/support/null_object.rb000066400000000000000000000001201320451746500212420ustar00rootroot00000000000000class NullObject private def method_missing(method, *args, &blk) end end rspec-rails-3.7.2/spec/support/shared_examples.rb000066400000000000000000000063351320451746500221240ustar00rootroot00000000000000require 'pathname' shared_examples_for "an rspec-rails example group mixin" do |type, *paths| let(:mixin) { described_class } def define_group_in(path, group_definition) path = Pathname(path) $_new_group = nil begin file = path + "whatever_spec.rb" Dir.mktmpdir("rspec-rails-app-root") do |dir| Dir.chdir(dir) do path.mkpath File.open(file, "w") do |f| f.write("$_new_group = #{group_definition}") end load file end end group = $_new_group return group ensure $_new_group = nil end end around(:example) do |ex| with_isolated_config(&ex) end it "adds does not add `:type` metadata on inclusion" do mixin = self.mixin group = RSpec.describe { include mixin } expect(group.metadata).not_to include(:type) end context 'when `infer_spec_type_from_file_location!` is configured' do before { RSpec.configuration.infer_spec_type_from_file_location! } paths.each do |path| context "for an example group defined in a file in the #{path} directory" do it "includes itself in the example group" do group = define_group_in path, "RSpec.describe" expect(group.included_modules).to include(mixin) end it "tags groups in that directory with `:type => #{type.inspect}`" do group = define_group_in path, "RSpec.describe" expect(group.metadata).to include(:type => type) end it "allows users to override the type" do group = define_group_in path, "RSpec.describe 'group', :type => :other" expect(group.metadata).to include(:type => :other) expect(group.included_modules).not_to include(mixin) end it "applies configured `before(:context)` hooks with `:type => #{type.inspect}` metadata" do block_run = false RSpec.configuration.before(:context, :type => type) { block_run = true } group = define_group_in path, "RSpec.describe('group') { it { } }" group.run(double.as_null_object) expect(block_run).to eq(true) end end end it "includes itself in example groups tagged with `:type => #{type.inspect}`" do group = define_group_in "spec/other", "RSpec.describe 'group', :type => #{type.inspect}" expect(group.included_modules).to include(mixin) end end context 'when `infer_spec_type_from_file_location!` is not configured' do it "includes itself in example groups tagged with `:type => #{type.inspect}`" do group = define_group_in "spec/other", "RSpec.describe 'group', :type => #{type.inspect}" expect(group.included_modules).to include(mixin) end paths.each do |path| context "for an example group defined in a file in the #{path} directory" do it "does not include itself in the example group" do group = define_group_in path, "RSpec.describe" expect(group.included_modules).not_to include(mixin) end it "does not tag groups in that directory with `:type => #{type.inspect}`" do group = define_group_in path, "RSpec.describe" expect(group.metadata).not_to include(:type) end end end end end rspec-rails-3.7.2/yard/000077500000000000000000000000001320451746500147155ustar00rootroot00000000000000rspec-rails-3.7.2/yard/template/000077500000000000000000000000001320451746500165305ustar00rootroot00000000000000rspec-rails-3.7.2/yard/template/default/000077500000000000000000000000001320451746500201545ustar00rootroot00000000000000rspec-rails-3.7.2/yard/template/default/fulldoc/000077500000000000000000000000001320451746500216045ustar00rootroot00000000000000rspec-rails-3.7.2/yard/template/default/fulldoc/html/000077500000000000000000000000001320451746500225505ustar00rootroot00000000000000rspec-rails-3.7.2/yard/template/default/fulldoc/html/css/000077500000000000000000000000001320451746500233405ustar00rootroot00000000000000rspec-rails-3.7.2/yard/template/default/fulldoc/html/css/rspec.css000066400000000000000000000004011320451746500251610ustar00rootroot00000000000000.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-3.7.2/yard/template/default/layout/000077500000000000000000000000001320451746500214715ustar00rootroot00000000000000rspec-rails-3.7.2/yard/template/default/layout/html/000077500000000000000000000000001320451746500224355ustar00rootroot00000000000000rspec-rails-3.7.2/yard/template/default/layout/html/setup.rb000066400000000000000000000003131320451746500241170ustar00rootroot00000000000000# 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