pax_global_header00006660000000000000000000000064136067011120014507gustar00rootroot0000000000000052 comment=108a422552fafbccbe4626a0f30e654806c6c3e6 rspec-rails-4.0.0.beta4/000077500000000000000000000000001360670111200147325ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/.document000066400000000000000000000000601360670111200165450ustar00rootroot00000000000000lib/**/*.rb - README.md LICENSE.md Changelog.md rspec-rails-4.0.0.beta4/.github/000077500000000000000000000000001360670111200162725ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/.github/FUNDING.yml000066400000000000000000000003221360670111200201040ustar00rootroot00000000000000# This file was generated on 2019-12-05T21:32:23+00:00 from the rspec-dev repo. # DO NOT modify it by hand as your changes will get lost the next time it is generated. github: [JonRowe] open_collective: rspec rspec-rails-4.0.0.beta4/.github/ISSUE_TEMPLATE/000077500000000000000000000000001360670111200204555ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000027341360670111200231550ustar00rootroot00000000000000--- name: Bug report about: Create a report to help us improve title: '' labels: '' assignees: '' --- ## What Ruby, Rails and RSpec versions are you using? Ruby version: Rails version: RSpec version: ## Observed behaviour ## Expected behaviour ## Can you provide an example app? rspec-rails-4.0.0.beta4/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000014221360670111200242010ustar00rootroot00000000000000--- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. rspec-rails-4.0.0.beta4/.gitignore000066400000000000000000000003561360670111200167260ustar00rootroot00000000000000tmp 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-4.0.0.beta4/.rspec000066400000000000000000000000511360670111200160430ustar00rootroot00000000000000--warnings --color --require spec_helper rspec-rails-4.0.0.beta4/.rubocop.yml000066400000000000000000000143021360670111200172040ustar00rootroot00000000000000inherit_from: - .rubocop_todo.yml AllCops: Exclude: # Templates are really ERB which Rubocop does not parse - 'lib/generators/rspec/*/templates/**/*' Layout/AccessModifierIndentation: Enabled: false Layout/AssignmentIndentation: Enabled: false Layout/ClosingParenthesisIndentation: Enabled: false Layout/EmptyLineAfterMagicComment: Enabled: false Layout/EmptyLineBetweenDefs: Enabled: false Layout/EmptyLinesAroundAccessModifier: Enabled: false Layout/EmptyLinesAroundBlockBody: Enabled: false Layout/ExtraSpacing: Enabled: false Layout/FirstArgumentIndentation: Enabled: false Layout/FirstArrayElementIndentation: Enabled: false Layout/HashAlignment: Enabled: false Layout/HeredocIndentation: Enabled: false Layout/MultilineMethodCallBraceLayout: Enabled: false Layout/MultilineMethodCallIndentation: Enabled: false Layout/MultilineOperationIndentation: Enabled: false Layout/ParameterAlignment: EnforcedStyle: with_first_parameter Layout/SpaceInsidePercentLiteralDelimiters: Enabled: false # We use spaces, so it's less of a change to stick with that. Layout/SpaceAroundEqualsInParameterDefault: EnforcedStyle: space Layout/SpaceAroundBlockParameters: Enabled: false Layout/SpaceAroundOperators: Enabled: false Layout/SpaceBeforeComma: Enabled: false Layout/SpaceInsideStringInterpolation: Enabled: false Lint/AssignmentInCondition: Enabled: false Lint/EmptyExpression: Enabled: false Lint/ImplicitStringConcatenation: Enabled: false Lint/NestedMethodDefinition: Enabled: false # Exceptions should be rescued with `Support::AllExceptionsExceptOnesWeMustNotRescue` Lint/RescueException: Enabled: true Lint/SuppressedException: 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 Metrics/AbcSize: Enabled: false Metrics/BlockLength: Enabled: false # Warns when the class is excessively long. Metrics/ClassLength: Max: 100 Metrics/PerceivedComplexity: Enabled: false # Who cares what we call the argument for binary operator methods? Naming/BinaryOperatorParameterName: Enabled: false Naming/ConstantName: Enabled: false Naming/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 Naming/HeredocDelimiterNaming: Enabled: false Naming/MemoizedInstanceVariableName: Enabled: false Naming/MethodParameterName: Enabled: false # We have too many special cases where we allow generator methods or prefer a # prefixed predicate due to it's improved readability. Naming/PredicateName: Enabled: false Naming/RescuedExceptionsVariableName: Enabled: false Naming/VariableNumber: Enabled: false Style/CollectionMethods: PreferredMethods: reduce: 'inject' Style/AccessModifierDeclarations: Enabled: false # "Use alias_method instead of alias" # We're fine with `alias`. Style/Alias: Enabled: false Style/BlockDelimiters: Enabled: false # "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. Style/CaseEquality: Enabled: false Style/ClassCheck: Enabled: false Style/ConditionalAssignment: Enabled: false Style/DateTime: Enabled: false # 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. Style/Documentation: Enabled: false Style/DoubleNegation: Enabled: false Style/EmptyMethod: Enabled: false Style/EmptyCaseCondition: Enabled: false Style/EmptyElse: Enabled: false Style/FormatString: EnforcedStyle: percent Style/FormatStringToken: Enabled: false Style/FrozenStringLiteralComment: Enabled: false Style/GuardClause: Enabled: false Style/IdenticalConditionalBranches: Enabled: false Style/IfUnlessModifierOfIfUnless: Enabled: false Style/IfInsideElse: Enabled: false Style/IfUnlessModifier: Enabled: false Style/MethodMissingSuper: Enabled: false Style/MissingRespondToMissing: Enabled: false Style/MixinUsage: Enabled: false Style/MultilineIfModifier: Enabled: false Style/MultipleComparison: Enabled: false Style/MutableConstant: Enabled: false Style/NestedModifier: Enabled: false Style/NestedParenthesizedCalls: Enabled: false Style/NumericPredicate: Enabled: false Style/ParallelAssignment: Enabled: false Style/ParenthesesAroundCondition: Enabled: false Style/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 Style/RegexpLiteral: Enabled: false Style/RedundantReturn: Enabled: false Style/RedundantParentheses: Enabled: false Style/RescueStandardError: Enabled: false # We haven't adopted the `fail` to signal exceptions vs `raise` for re-raises convention. Style/SignalException: Enabled: false # This rule favors constant names from the English standard library which we don't load. Style/SpecialGlobalVars: Enabled: false Style/StderrPuts: Enabled: false Style/StringLiteralsInInterpolation: Enabled: false Style/StructInheritance: Enabled: false # We don't care about single vs double qoutes. Style/StringLiterals: Enabled: false Style/SymbolArray: Enabled: false Style/SymbolProc: Enabled: false Style/TernaryParentheses: Enabled: false Style/TrailingCommaInArrayLiteral: Enabled: false Style/TrailingCommaInHashLiteral: Enabled: false Style/TrailingCommaInArguments: Enabled: false Style/TrivialAccessors: AllowDSLWriters: true AllowPredicates: true ExactNameMatch: true Style/TrailingUnderscoreVariable: Enabled: false Style/YodaCondition: Enabled: false Style/ZeroLengthPredicate: Enabled: false rspec-rails-4.0.0.beta4/.rubocop_todo.yml000066400000000000000000000017421360670111200202350ustar00rootroot00000000000000# ruby 1.8.7 required trailing dots Layout/DotPosition: EnforcedStyle: trailing # Over time we'd like to get this down, but this is what we're at now. Metrics/CyclomaticComplexity: Max: 9 # default: 6 # Over time we'd like to get this down, but this is what we're at now. Layout/LineLength: Max: 186 # default: 80 # Over time we'd like to get this down, but this is what we're at now. Metrics/MethodLength: Max: 43 # default: 10 # each_with_object was unavailable on ruby 1.8.7 Style/EachWithObject: Enabled: false # the new lambda syntax was not supported in ruby 1.8.7 Style/Lambda: Enabled: false # we couldn't use named matches in ruby 1.8.7 Style/PerlBackrefs: Exclude: - lib/generators/rspec/scaffold/scaffold_generator.rb # On 1.8 `proc` was `lambda`, so we used `Proc.new` to ensure we got 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/ Style/Proc: Enabled: false rspec-rails-4.0.0.beta4/.travis.yml000066400000000000000000000073661360670111200170570ustar00rootroot00000000000000language: ruby # 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/update_rubygems_and_install_bundler - script/clone_all_rspec_repos before_script: # Rails 4+ complains with a bundler rails binstub in PROJECT_ROOT/bin/ - rm -f bin/rails - bundle exec rails --version script: "script/run_build 2>&1" # In order to install old Rubies, we need to use old Ubuntu distibution. dist: trusty matrix: include: # Rails 6 builds - rvm: jruby-head jdk: oraclejdk11 env: - RAILS_VERSION='~> 6.0.0' - JRUBY_OPT=--dev - JAVA_OPTS="--add-opens java.base/sun.nio.ch=org.jruby.dist --add-opens java.base/java.io=org.jruby.dist --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.security=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.security.cert=ALL-UNNAMED --add-opens=java.base/java.util.zip=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.util.regex=ALL-UNNAMED --add-opens=java.base/java.net=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/javax.crypto=ALL-UNNAMED --add-opens=java.management/sun.management=ALL-UNNAMED" - rvm: 2.6.3 env: RAILS_VERSION='~> 6.0.0' - rvm: 2.5.5 env: RAILS_VERSION='~> 6.0.0' # Rails 5.2 builds >= 2.2.2 - rvm: jruby-head jdk: oraclejdk11 env: - RAILS_VERSION='~> 5.2.0' - JRUBY_OPT=--dev - JAVA_OPTS="--add-opens java.base/sun.nio.ch=org.jruby.dist --add-opens java.base/java.io=org.jruby.dist --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.security=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.security.cert=ALL-UNNAMED --add-opens=java.base/java.util.zip=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.util.regex=ALL-UNNAMED --add-opens=java.base/java.net=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/javax.crypto=ALL-UNNAMED --add-opens=java.management/sun.management=ALL-UNNAMED" - rvm: 2.6.3 env: RAILS_VERSION='~> 5.2.0' - rvm: 2.5.5 env: RAILS_VERSION='~> 5.2.0' - rvm: 2.4.6 env: RAILS_VERSION='~> 5.2.0' - rvm: 2.3.8 env: RAILS_VERSION='~> 5.2.0' # Rails 5.1 Builds >= 2.2.2 - rvm: 2.6.3 env: RAILS_VERSION='~> 5.1.0' - rvm: 2.5.5 env: RAILS_VERSION='~> 5.1.0' - rvm: 2.4.6 env: RAILS_VERSION='~> 5.1.0' - rvm: 2.3.8 env: RAILS_VERSION='~> 5.1.0' # Rails 5.0 Builds >= 2.2.2 - rvm: 2.6.3 env: RAILS_VERSION='~> 5.0.0' - rvm: 2.5.5 env: RAILS_VERSION='~> 5.0.0' - rvm: 2.4.6 env: RAILS_VERSION='~> 5.0.0' - rvm: 2.3.8 env: RAILS_VERSION='~> 5.0.0' fast_finish: true rspec-rails-4.0.0.beta4/.yardopts000066400000000000000000000004201360670111200165740ustar00rootroot00000000000000--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-4.0.0.beta4/BUILD_DETAIL.md000066400000000000000000000124321360670111200171370ustar00rootroot00000000000000 # 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 list 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](https://yardoc.org/) for API documentation on the [rspec.info site](https://rspec.info/). Our commitment to [SemVer](https://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-4.0.0.beta4/CODE_OF_CONDUCT.md000066400000000000000000000054441360670111200175400ustar00rootroot00000000000000 # 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 https://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 [https://contributor-covenant.org/version/1/3/0/][version] [homepage]: https://contributor-covenant.org [version]: https://contributor-covenant.org/version/1/3/0/ rspec-rails-4.0.0.beta4/CONTRIBUTING.md000066400000000000000000000066741360670111200172000ustar00rootroot00000000000000 # 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?template=bug_report.md) - by [suggesting new features](https://github.com/rspec/rspec-rails/issues/new?template=feature_request.md) - by improving RSpec's [Relish](https://relishapp.com/rspec) or [API](https://rspec.info/documentation/) documentation - by improving [RSpec's website](https://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 issues labels definition ### `Your first PR` issues These issues are the ones that we be believe are best suited for new contributors to get started on. They represent a potential meaningful contribution to the project that should not be too hard to pull off. ### `Needs reproduction case` issues These issues are ones that have been labelled by the maintainers that we believe do not currently have enough information to be reproduced the RSpec team. While not directly counted by the GitHub contribution graph, we consider helping us to reproduce the issue with a repro case as an extremely meaningful contribution. ### `Has reproduction case` issues These issues are the ones that have reproduction cases, able to start working on immediately. These are good ones to tackle to help us actively fix bugs. ## Maintenance branches Maintenance branches are how we manage the different supported point releases of RSpec. As such, while they might look like good candidates to merge into master, please do not open pull requests to merge them. ## How do the cukes work? The cucumber features for RSpec rails document how it works, but are also quasi executable tests for the framework. They execute in the context of a pre-setup Rails app. 1. Before the cucumber specs run, the directory `tmp/aruba` is cleared 2. If the example app hasn't already been created, `bundle exec rake generate:app generate:stuff` is executed. 3. The example app is copied in to `tmp/aruba` 4. Everything in `tmp/aruba/spec/*` is deleted apart from `spec/spec_helper.rb` and `spec/rails_helper.rb` 5. the cucumber suite executes, creating files in that app and executing them The best way to debug the app is to run a failing cucumber feature, which will leave the test files intact in `tmp/aruba`, then you can cd in to that director and run it in the bundle context of the aruba app. rspec-rails-4.0.0.beta4/Capybara.md000066400000000000000000000041721360670111200170020ustar00rootroot00000000000000rspec-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-4.0.0.beta4/Changelog.md000066400000000000000000001176461360670111200171620ustar00rootroot00000000000000### 4.0.0.beta4 [Full Changelog](https://github.com/rspec/rspec-rails/compare/v4.0.0.beta3...v4.0.0.beta4) Enhancements: * Add argument matcher support to `have_enqueued_*` matchers. (Phil Pirozhkov, #2206) * Switch generated templates to use ruby 1.9 hash keys. (Tanbir Hasan, #2224) * Add `have_been_performed`/`have_performed_job`/`perform_job` ActiveJob matchers (Isaac Seymour, #1785) * Default to generating request specs rather than controller specs when generating a controller (Luka Lüdicke, #2222) Bug Fixes: * Prevent `driven_by(:selenium)` being called due to hook precedence. (Takumi Shotoku, #2188) * Prevent a `WrongScopeError` being thrown during loading fixtures on Rails 6.1 development version. (Edouard Chin, #2215) * Fix Mocha mocking support with `should`. (Phil Pirozhkov, #2256) ### 4.0.0.beta3 [Full Changelog](https://github.com/rspec/rspec-rails/compare/v4.0.0.beta2...v4.0.0.beta3) Enhancements: * Adds support for JRuby on Rails 5.2 and 6 * Add support for parameterised mailers (Ignatius Reza, #2125) * Add ActionMailbox spec helpers and test type (James Dabbs, #2119) * Add ActionCable spec helpers and test type (Vladimir Dementyev, #2113) * Add support for partial args when using `have_enqueued_mail` (Ignatius Reza, #2118, #2125) * Add support for time arguments for `have_enqueued_job` (@alpaca-tc, #2157) * Improve path parsing in view specs render options. (John Hawthorn, #2115) * Add routing spec template as an option for generating controller specs. (David Revelo, #2134) Bug Fixes: * Replace `before_teardown` as well as `after_teardown` to ensure screenshots are generated correctly. (Jon Rowe, #2164) * `ActionView::FixtureResolver#hash` has been renamed to `ActionView::FixtureResolver#data`. (Penelope Phippen, #2076) * Add missing require for `have_enqueued_mail` matcher. (Ignatius Reza, #2117) ### 4.0.0.beta2 [Full Changelog](https://github.com/rspec/rspec-rails/compare/v4.0.0.beta1...v4.0.0.beta2) Bug Fixes: * Fix version dependencies in gemspec. ### 4.0.0.beta1 [Full Changelog](https://github.com/rspec/rspec-rails/compare/v3.9.0...v4.0.0.beta1) Enhancements: * Adds support for Rails 6. (Penelope Phippen, Benoit Tigeot, Jon Rowe, #2071) Bug Fixes: * `EmptyTemplateHandler.call` now needs to support an additional argument in Rails 6. (Pavel Rosický, #2089) * Suppress warning from `SQLite3Adapter.represent_boolean_as_integer` which is deprecated. (Pavel Rosický, #2092) * `ActionView::Template#formats` has been deprecated and replaced by `ActionView::Template#format`(Seb Jacobs, #2100) Breaking Changes: * Drops support for Rails below 5.0 * Drops support for Ruby below 2.3 ### 3.9.0 / 2019-10-08 [Full Changelog](https://github.com/rspec/rspec-rails/compare/v3.8.3...v3.9.0) Enhancements * Use `__dir__` instead of `__FILE__` in generated `rails_helper.rb` where supported. (OKURA Masafumi, #2048) * Add `have_enqueued_mail` matcher as a "super" matcher to the `ActiveJob` matchers making it easier to match on `ActiveJob` delivered emails. (Joel Lubrano, #2047) * Add generator for system specs on Rails 5.1 and above. (Andrzej Sliwa, #1933) * Add generator for generator specs. (@ConSou, #2085) * Add option to generate routes when generating controller specs. (David Revelo, #2134) Bug Fixes: * Make the `ActiveJob` matchers fail when multiple jobs are queued for negated matches. e.g. `expect { job; job; }.to_not have_enqueued_job`. (Emric Istanful, #2069) ### 3.8.3 / 2019-10-03 [Full Changelog](https://github.com/rspec/rspec-rails/compare/v3.8.2...v3.8.3) Bug Fixes: * Namespaced fixtures now generate a `/` seperated path rather than an `_`. (@nxlith, #2077) * Check the arity of `errors` before attempting to use it to generate the `be_valid` error message. (Kevin Kuchta, #2096) ### 3.8.2 / 2019-01-13 [Full Changelog](https://github.com/rspec/rspec-rails/compare/v3.8.1...v3.8.2) Bug Fixes: * Fix issue with generator for preview specs where `Mailer` would be duplicated in the name. (Kohei Sugi, #2037) * Fix the request spec generator to handle namespaced files. (Kohei Sugi, #2057) * Further truncate system test filenames to handle cases when extra words are prepended. (Takumi Kaji, #2058) * Backport: Make the `ActiveJob` matchers fail when multiple jobs are queued for negated matches. e.g. `expect { job; job; }.to_not have_enqueued_job (Emric Istanful, #2069) ### 3.8.1 / 2018-10-23 [Full Changelog](https://github.com/rspec/rspec-rails/compare/v3.8.0...v3.8.1) Bug Fixes: * Fix `NoMethodError: undefined method 'strip'` when using a `Pathname` object as the fixture file path. (Aaron Kromer, #2026) * When generating feature specs, do not duplicate namespace in the path name. (Laura Paakkinen, #2034) * Prevent `ActiveJob::DeserializationError` from being issued when `ActiveJob` matchers de-serialize arguments. (@aymeric-ledorze, #2036) ### 3.8.0 / 2018-08-04 [Full Changelog](https://github.com/rspec/rspec-rails/compare/v3.7.2...v3.8.0) Enhancements: * Improved message when migrations are pending in the default `rails_helper.rb` (Koichi ITO, #1924) * `have_http_status` matcher now supports Rails 5.2 style response symbols (Douglas Lovell, #1951) * Change generated Rails helper to match Rails standards for Rails.root (Alessandro Rodi, #1960) * At support for asserting enqueued jobs have no wait period attached. (Brad Charna, #1977) * Cache instances of `ActionView::Template` used in `stub_template` resulting in increased performance due to less allocations and setup. (Simon Coffey, #1979) * Rails scaffold generator now respects longer namespaces (e.g. api/v1/\). (Laura Paakkinen, #1958) Bug Fixes: * Escape quotation characters when producing method names for system spec screenshots. (Shane Cavanaugh, #1955) * Use relative path for resolving fixtures when `fixture_path` is not set. (Laurent Cobos, #1943) * Allow custom template resolvers in view specs. (@ahorek, #1941) ### 3.7.2 / 2017-11-20 [Full Changelog](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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 [https://rubydoc.info/gems/rspec-rails/file/Capybara.md](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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](https://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-4.0.0.beta4/DEVELOPMENT.md000066400000000000000000000115211360670111200170360ustar00rootroot00000000000000 # Development Setup Generally speaking, you only need to clone the project and install the dependencies with [Bundler](https://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](https://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`](https://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](https://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-4.0.0.beta4/Gemfile000066400000000000000000000027501360670111200162310ustar00rootroot00000000000000source "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 'github-markup', '~> 3.0.3' gem 'redcarpet', '~> 3.4.0', platforms: [:ruby] gem 'relish', '~> 0.7.1' end platforms :jruby do gem "jruby-openssl" end case RAILS_VERSION when /master/ MAJOR = 6 MINOR = 0 when /stable/ MAJOR = 6 MINOR = 0 when nil, false, "" MAJOR = 5 MINOR = 0 else match = /(\d+)(\.|-)(\d+)/.match(RAILS_VERSION) MAJOR, MINOR = match.captures.map(&:to_i).compact end if MAJOR >= 6 gem 'selenium-webdriver', '~> 3.5', require: false gem 'sqlite3', '~> 1.4', platforms: [:ruby] else gem 'sqlite3', '~> 1.3.6', platforms: [:ruby] end gem 'ffi', '~> 1.9.25' gem 'rake', '~> 12' gem 'mime-types', "~> 3" gem 'capybara', '~> 2.13', require: false if MAJOR < 6 gem 'nokogiri', '1.9.1' else gem 'nokogiri', '>= 1.10.4' end gem "rubyzip", '~> 1.2' gem 'rubocop', '~> 0.79.0' 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-4.0.0.beta4/Gemfile-custom.sample000066400000000000000000000003711360670111200210160ustar00rootroot00000000000000group :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' end end rspec-rails-4.0.0.beta4/Gemfile-rails-dependencies000066400000000000000000000041041360670111200217600ustar00rootroot00000000000000version_file = File.expand_path("../.rails-version", __FILE__) # FIXME: rack 2.1.0 introduces a deprecation warning that rails is triggering, # but in later versions this warning will be removed. Get rid of this hack once # rack 2.1.0+ is out. gem 'rack', '!= 2.1.0' case version = ENV['RAILS_VERSION'] || (File.exist?(version_file) && File.read(version_file).chomp) || '' when /master/ gem "rails", :git => "https://github.com/rails/rails.git" gem "arel", :git => "https://github.com/rails/arel.git" gem "journey", :git => "https://github.com/rails/journey.git" gem "activerecord-deprecated_finders", :git => "https://github.com/rails/activerecord-deprecated_finders.git" gem "web-console", :git => "https://github.com/rails/web-console", :group => :development gem 'coffee-rails', :git => "https://github.com/rails/coffee-rails.git" gem 'rack', :git => 'https://github.com/rack/rack.git' gem 'i18n', :git => 'https://github.com/svenfuchs/i18n.git', :branch => 'master' gem 'sprockets', :git => 'https://github.com/rails/sprockets.git', :branch => 'master' gem 'sprockets-rails', :git => 'https://github.com/rails/sprockets-rails.git', :branch => 'master' gem 'puma', "3.12.1" gem 'activerecord-jdbcsqlite3-adapter', git: 'https://github.com/jruby/activerecord-jdbc-adapter', platforms: [:jruby] when /stable$/ gem_list = %w[rails railties actionmailer actionpack activerecord activesupport activejob actionview] gem 'puma', "3.12.1" if version > '5-0-stable' gem 'activerecord-jdbcsqlite3-adapter', git: 'https://github.com/jruby/activerecord-jdbc-adapter', platforms: [:jruby] gem_list.each do |rails_gem| gem rails_gem, :git => "https://github.com/rails/rails.git", :branch => version end when nil, false, "" gem "rails", "~> 5.0.0" gem 'activerecord-jdbcsqlite3-adapter', platforms: [:jruby] else gem "rails", version gem "puma" if version >= '5-1-stable' if version.gsub(/[^\d\.]/,'').to_f >= 6.0 gem "activerecord-jdbcsqlite3-adapter", "~> 60.0.rc1", platforms: [:jruby] else gem 'activerecord-jdbcsqlite3-adapter', platforms: [:jruby] end end rspec-rails-4.0.0.beta4/Gemfile-rspec-dependencies000066400000000000000000000006721360670111200217700ustar00rootroot00000000000000branch = 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 => "https://github.com/rspec/#{lib}.git", :branch => branch, :require => false end end rspec-rails-4.0.0.beta4/LICENSE.md000066400000000000000000000023221360670111200163350ustar00rootroot00000000000000The 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-4.0.0.beta4/README.md000066400000000000000000000351541360670111200162210ustar00rootroot00000000000000# rspec-rails [![Build Status][]][travis-ci] [![Code Climate][]][code-climate] [![Gem Version][]](gem-version) `rspec-rails` brings the [RSpec][] testing framework to [Ruby on Rails][] as a drop-in alternative to its default testing framework, Minitest. In RSpec, tests are not just scripts that verify your application code. They’re also specifications (or _specs,_ for short): detailed explanations of how the application is supposed to behave, expressed in plain English. Use **[`rspec-rails` 1.x][]** for Rails 2.x. [Build Status]: https://secure.travis-ci.org/rspec/rspec-rails.svg?branch=master [travis-ci]: https://travis-ci.org/rspec/rspec-rails [Code Climate]: https://codeclimate.com/github/rspec/rspec-rails.svg [code-climate]: https://codeclimate.com/github/rspec/rspec-rails [Gem Version]: https://badge.fury.io/rb/rspec-rails.svg [gem-version]: https://badge.fury.io/rb/rspec-rails [RSpec]: https://rspec.info/ [Ruby on Rails]: https://rubyonrails.org/ [`rspec-rails` 1.x]: https://github.com/dchelimsky/rspec-rails ## Installation 1. Add `rspec-rails` to **both** the `:development` and `:test` groups of your app’s `Gemfile`: ```ruby # Run against the latest stable release group :development, :test do gem 'rspec-rails', '~> 4.0' end # Or, run against the master branch # (requires master-branch versions of all related RSpec libraries) group :development, :test do %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 end ``` (Adding it to the `:development` group is not strictly necessary, but without it, generators and rake tasks must be preceded by `RAILS_ENV=test`.) 2. Then, in your project directory: ```sh # Download and install $ bundle install # Generate boilerplate configuration files # (check the comments in each generated file for more information) $ rails generate rspec:install create .rspec create spec create spec/spec_helper.rb create spec/rails_helper.rb ``` ## Upgrading If your project is already using an older version of `rspec-rails`, upgrade to the latest version with: ```sh $ bundle update rspec-rails ``` RSpec follows [semantic versioning](https://semver.org/), which means that “major version” upgrades (_e.g.,_ 2.x → 3.x) come with **breaking changes**. If you’re upgrading from version 2.x or below, read the [`rspec-rails` upgrade notes][] to find out what to watch out for. Be sure to check the general [RSpec upgrade notes][] as well. [`rspec-rails` upgrade notes]: https://www.relishapp.com/rspec/rspec-rails/docs/upgrade [RSpec upgrade notes]: https://relishapp.com/rspec/docs/upgrade ## Usage ### Creating boilerplate specs with `rails generate` ```sh # RSpec hooks into built-in generators $ rails generate model user invoke active_record create db/migrate/20181017040312_create_users.rb create app/models/user.rb invoke rspec create spec/models/user_spec.rb # RSpec also provides its own spec file generators $ rails generate rspec:model user create spec/models/user_spec.rb # List all RSpec generators $ rails generate --help | grep rspec ``` ### Running specs ```sh # Default: Run all spec files (i.e., those matching spec/**/*_spec.rb) $ bundle exec rspec # Run all spec files in a single directory (recursively) $ bundle exec rspec spec/models # Run a single spec file $ bundle exec rspec spec/controllers/accounts_controller_spec.rb # Run a single example from a spec file (by line number) $ bundle exec rspec spec/controllers/accounts_controller_spec.rb:8 # See all options for running specs $ bundle exec rspec --help ``` **Optional:** If `bundle exec rspec` is too verbose for you, you can generate a binstub at `bin/rspec` and use that instead: ```sh $ bundle binstubs rspec-core ``` ## RSpec DSL Basics (or, how do I write a spec?) In RSpec, application behavior is described **first in (almost) plain English, then again in test code**, like so: ```ruby RSpec.describe 'Post' do # context 'before publication' do # (almost) plain English it 'cannot have comments' do # expect { Post.create.comments.create! }.to raise_error(ActiveRecord::RecordInvalid) # test code end end end ``` Running `rspec` will execute this test code, and then use the plain-English descriptions to generate a report of where the application conforms to (or fails to meet) the spec: ``` $ rspec --format documentation spec/models/post_spec.rb Post before publication cannot have comments Failures: 1) Post before publication cannot have comments Failure/Error: expect { Post.create.comments.create! }.to raise_error(ActiveRecord::RecordInvalid) expected ActiveRecord::RecordInvalid but nothing was raised # ./spec/models/post.rb:4:in `block (3 levels) in ' Finished in 0.00527 seconds (files took 0.29657 seconds to load) 1 example, 1 failure Failed examples: rspec ./spec/models/post_spec.rb:3 # Post before publication cannot have comments ``` For an in-depth look at the RSpec DSL, including lots of examples, read the official Cucumber documentation for [RSpec Core][]. [RSpec Core]: https://relishapp.com/rspec/rspec-core/docs ### Helpful Rails Matchers In RSpec, assertions are called _expectations,_ and every expectation is built around a _matcher._ When you `expect(a).to eq(b)`, you’re using the `eq` matcher. In addition to [the matchers that come standard in RSpec][], here are some extras that make it easier to test the various parts of a Rails system: | RSpec matcher | Delegates to | Available in | Notes | | ------------------------ | ----------------- | ------------------------------- | -------------------------------------------------------- | | [`be_a_new`][] | | all | primarily intended for controller specs | | [`render_template`][] | `assert_template` | request / controller / view | use with `expect(response).to` | | [`redirect_to`][] | `assert_redirect` | request / controller | use with `expect(response).to` | | [`route_to`] | `assert_routing` | routing / controller | replaces `route_for` from version 1.x | | [`be_routable`] | | routing / controller | usu. for `expect(...).not_to be_routable` | | [`have_http_status`][] | | request / controller / feature | | | [`match_array`][] | | all | for comparing arrays of ActiveRecord objects | | [`have_been_enqueued`][] | | all | requires config: `ActiveJob::Base.queue_adapter = :test` | | [`have_enqueued_job`][] | | all | requires config: `ActiveJob::Base.queue_adapter = :test` | Follow the links above for examples of how each matcher is used. [the matchers that come standard in RSpec]: https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers [`be_a_new`]: https://relishapp.com/rspec/rspec-rails/docs/matchers/be-a-new-matcher [`render_template`]: https://relishapp.com/rspec/rspec-rails/docs/matchers/render-template-matcher [`redirect_to`]: https://relishapp.com/rspec/rspec-rails/docs/matchers/redirect-to-matcher [`route_to`]: https://relishapp.com/rspec/rspec-rails/docs/routing-specs/route-to-matcher [`be_routable`]: https://relishapp.com/rspec/rspec-rails/docs/routing-specs/be-routable-matcher [`have_http_status`]: https://relishapp.com/rspec/rspec-rails/docs/matchers/have-http-status-matcher [`match_array`]: https://relishapp.com/rspec/rspec-rails/docs/matchers/activerecord-relation-match-array [`have_been_enqueued`]: https://relishapp.com/rspec/rspec-rails/docs/matchers/have-been-enqueued-matcher [`have_enqueued_job`]: https://relishapp.com/rspec/rspec-rails/docs/matchers/have-enqueued-job-matcher ### What else does RSpec Rails add? For a comprehensive look at RSpec Rails’ features, read the [official Cucumber documentation][]. [official Cucumber documentation]: https://relishapp.com/rspec/rspec-rails/docs ## What tests should I write? RSpec Rails defines ten different _types_ of specs for testing different parts of a typical Rails application. Each one inherits from one of Rails’ built-in `TestCase` classes, meaning the helper methods provided by default in Rails tests are available in RSpec, as well. | Spec type | Corresponding Rails test class | | -------------- | -------------------------------- | | [model][] | | | [controller][] | [`ActionController::TestCase`][] | | [mailer][] | `ActionMailer::TestCase` | | [job][] | | | [view][] | `ActionView::TestCase` | | [routing][] | | | [helper][] | `ActionView::TestCase` | | [request][] | [`ActionDispatch::IntegrationTest`][] | | [feature][] | | | [system][] | [`ActionDispatch::SystemTestCase`][] | Follow the links above to see examples of each spec type, or for official Rails API documentation on the given `TestCase` class. > **Note: This is not a checklist.** > > Ask a hundred developers how to test an application, > and you’ll get a hundred different answers. > > RSpec Rails provides thoughtfully selected features > to encourage good testing practices, but there’s no “right” way to do it. > Ultimately, it’s up to you to decide how your test suite will be composed. When creating a spec file, assign it a type in the top-level `describe` block, like so: ```ruby # spec/models/user_spec.rb RSpec.describe User, type: :model do ... ``` [request]: https://relishapp.com/rspec/rspec-rails/docs/request-specs/request-spec [feature]: https://www.relishapp.com/rspec/rspec-rails/docs/feature-specs/feature-spec [system]: https://relishapp.com/rspec/rspec-rails/docs/system-specs/system-spec [model]: https://www.relishapp.com/rspec/rspec-rails/docs/model-specs [controller]: https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs [mailer]: https://relishapp.com/rspec/rspec-rails/docs/mailer-specs [job]: https://relishapp.com/rspec/rspec-rails/docs/job-specs/job-spec [view]: https://www.relishapp.com/rspec/rspec-rails/docs/view-specs/view-spec [routing]: https://www.relishapp.com/rspec/rspec-rails/docs/routing-specs [helper]: https://www.relishapp.com/rspec/rspec-rails/docs/helper-specs/helper-spec [`ActionDispatch::IntegrationTest`]: https://api.rubyonrails.org/classes/ActionDispatch/IntegrationTest.html [`ActionDispatch::SystemTestCase`]: https://api.rubyonrails.org/classes/ActionDispatch/SystemTestCase.html [`ActionController::TestCase`]: https://api.rubyonrails.org/classes/ActionController/TestCase.html [in the appropriate folder]: https://relishapp.com/rspec/rspec-rails/docs/directory-structure ### System specs, feature specs, request specs–what’s the difference? RSpec Rails provides some end-to-end (entire application) testing capability to specify the interaction with the client. #### System specs Also called **acceptance tests**, **browser tests**, or **end-to-end tests**, system specs test the application from the perspective of a _human client._ The test code walks through a user’s browser interactions, * `visit '/login'` * `fill_in 'Name', with: 'jdoe'` and the expectations revolve around page content. * `expect(page).to have_text('Welcome')` Because system specs are a wrapper around Rails’ built-in `SystemTestCase`, they’re only available on Rails 5.1+. (Feature specs serve the same purpose, but without this dependency.) #### Feature specs Before Rails introduced system testing facilities, feature specs were the only spec type for end-to-end testing. While the RSpec team now [officially recommends system specs][] instead, feature specs are still fully supported, look basically identical, and work on older versions of Rails. On the other hand, feature specs require non-trivial configuration to get some important features working, like JavaScript testing or making sure each test runs with a fresh DB state. With system specs, this configuration is provided out-of-the-box. Like system specs, feature specs require the [Capybara][] gem. Rails 5.1+ includes it by default as part of system tests, but if you don’t have the luxury of upgrading, be sure to add it to the `:test` group of your `Gemfile` first: ```ruby group :test do gem "capybara" end ``` [officially recommends system specs]: https://rspec.info/blog/2017/10/rspec-3-7-has-been-released/#rails-actiondispatchsystemtest-integration-system-specs [Capybara]: https://github.com/teamcapybara/capybara #### Request specs Request specs are for testing the application from the perspective of a _machine client._ They begin with an HTTP request and end with the HTTP response, so they’re faster than feature specs, but do not examine your app’s UI or JavaScript. Request specs provide a high-level alternative to controller specs. In fact, as of RSpec 3.5, both the Rails and RSpec teams [discourage directly testing controllers][] in favor of functional tests like request specs. When writing them, try to answer the question, “For a given HTTP request (verb + path + parameters), what HTTP response should the application return?” [discourage directly testing controllers]: https://rspec.info/blog/2016/07/rspec-3-5-has-been-released/#rails-support-for-rails-5 ## Contributing - [Build details](BUILD_DETAIL.md) - [Code of Conduct](CODE_OF_CONDUCT.md) - [Detailed contributing guide](CONTRIBUTING.md) Once you’ve cloned the repo and [set up the environment](DEVELOPMENT.md), you can run the specs and Cucumber features, or submit a pull request. ## See Also ### RSpec base libraries * * * * ### Recommended third-party extensions * [FactoryBot](https://github.com/thoughtbot/factory_bot) * [Capybara](https://github.com/jnicklas/capybara) (Included by default in Rails 5.1+. Note that [additional configuration is required][] to use the Capybara DSL anywhere other than system specs and feature specs.) [additional configuration is required]: https://rubydoc.info/gems/rspec-rails/file/Capybara.md rspec-rails-4.0.0.beta4/README_DEV.md000066400000000000000000000015511360670111200167110ustar00rootroot00000000000000# 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-4.0.0.beta4/Rakefile000066400000000000000000000146331360670111200164060ustar00rootroot00000000000000require "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/version" 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", "~> 5.2.0")[/\d[\.-]\d/] if version == "master" || version.nil? version = Float::INFINITY end tags = [] if version.to_f >= 5.1 tags << "~@rails_pre_5.1" end if version.to_f == 5.0 tags << "~@system_test" end if version.to_f >= 6.0 tags << "~@rails_pre_6" end if version.to_f < 6.0 tags << "~@rails_post_6" 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-bootsnap -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-bootsnap --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-4.0.0.beta4/Thorfile000066400000000000000000000005461360670111200164360ustar00rootroot00000000000000class 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-4.0.0.beta4/appveyor.yml000066400000000000000000000016441360670111200173270ustar00rootroot00000000000000# This file was generated on 2019-12-18T14:01:39+00: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 cache: - vendor/bundle install: - set PATH=C:\Ruby%RUBY_VERSION%\bin;%PATH% - bundle config --local path vendor/bundle - bundle install - cinst ansicon before_test: - ruby --version - gem --version - bundle --version test_script: - bundle exec rspec --backtrace environment: matrix: - ruby_version: 23-x64 - ruby_version: 24-x64 - ruby_version: 25-x64 - ruby_version: 26-x64 rspec-rails-4.0.0.beta4/benchmarks/000077500000000000000000000000001360670111200170475ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/benchmarks/before_block_capture_block_vs_yield.rb000066400000000000000000000150361360670111200266100ustar00rootroot00000000000000require '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-4.0.0.beta4/cucumber.yml000066400000000000000000000002361360670111200172630ustar00rootroot00000000000000default: --require features --format progress --tags ~@wip pretty: --require features --format pretty --tags ~@wip wip: --require features --tags @wip rspec-rails-4.0.0.beta4/example_app_generator/000077500000000000000000000000001360670111200212735ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/app/000077500000000000000000000000001360670111200220535ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/app/views/000077500000000000000000000000001360670111200232105ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/app/views/foo.html000066400000000000000000000000411360670111200246540ustar00rootroot00000000000000Static template named 'foo.html' rspec-rails-4.0.0.beta4/example_app_generator/app/views/some_templates/000077500000000000000000000000001360670111200262315ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/app/views/some_templates/bar.html000066400000000000000000000000411360670111200276560ustar00rootroot00000000000000Static template named 'bar.html' rspec-rails-4.0.0.beta4/example_app_generator/config/000077500000000000000000000000001360670111200225405ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/config/initializers/000077500000000000000000000000001360670111200252465ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/config/initializers/sqlite3_fix.rb000066400000000000000000000002561360670111200300300ustar00rootroot00000000000000if Rails.application.config.respond_to?(:active_record) && !(RUBY_ENGINE == "jruby") Rails.application.config.active_record.sqlite3.represent_boolean_as_integer = true end rspec-rails-4.0.0.beta4/example_app_generator/generate_action_mailer_specs.rb000066400000000000000000000021451360670111200274770ustar00rootroot00000000000000require 'active_support' require 'active_support/core_ext/module' 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'] ExampleApp::Application.configure do config.action_mailer.default_url_options = { :host => ENV['DEFAULT_URL'] } end 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/ comment_lines 'spec/support/default_preview_path', /active_storage/ end copy_file 'spec/verify_mailer_preview_path_spec.rb' end rspec-rails-4.0.0.beta4/example_app_generator/generate_app.rb000066400000000000000000000062151360670111200242560ustar00rootroot00000000000000require 'nokogiri' 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') sqlite_initializer = File.join(rspec_rails_repo_path, "example_app_generator/config/initializers/sqlite3_fix.rb") 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.*/, "" gsub_file "Gemfile", /.*gem..sqlite3.*/, "gem 'sqlite3', '~> 1.3.6'" gsub_file "Gemfile", /.*bootsnap.*/, "" if Rails::VERSION::STRING >= '5.0.0' append_to_file('Gemfile', "gem 'rails-controller-testing'\n") end if Rails::VERSION::STRING >= '6' gsub_file "Gemfile", /.*gem..sqlite3.*/, "gem 'sqlite3', '~> 1.4'" gsub_file "Gemfile", /.*rails-controller-testing.*/, "gem 'rails-controller-testing', git: 'https://github.com/rails/rails-controller-testing'" end if Rails::VERSION::STRING >= "5.1.0" if RUBY_VERSION < "2.4" gsub_file "Gemfile", /.*capybara.*/, "gem 'capybara', '~> 3.15.0'" end if Rails::VERSION::STRING >= "5.2.0" gsub_file "Gemfile", /.*chromedriver-helper.*/, "gem 'webdrivers', '< 4.0.0'" else gsub_file "Gemfile", /.*chromedriver-helper.*/, "gem 'webdrivers'" end end if Rails::VERSION::STRING >= '5.2.0' && Rails::VERSION::STRING < '6' copy_file sqlite_initializer, 'config/initializers/sqlite3_fix.rb' 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. if RUBY_ENGINE != "jruby" append_to_file 'Gemfile', "gem 'nokogiri', '#{Nokogiri::VERSION}'\n" else gsub_file "Gemfile", /.*jdbc.*/, "" end # Use our version of RSpec and Rails append_to_file 'Gemfile', <<-EOT.gsub(/^ +\|/, '') |gem 'rake', '>= 10.0.0' | |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-4.0.0.beta4/example_app_generator/generate_stuff.rb000066400000000000000000000074371360670111200246340ustar00rootroot00000000000000require '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') 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('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 begin require 'action_cable' require 'action_cable/test_helper' generate('channel chat') 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-4.0.0.beta4/example_app_generator/log/000077500000000000000000000000001360670111200220545ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/log/development.log000066400000000000000000000000001360670111200250670ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/no_active_record/000077500000000000000000000000001360670111200246005ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/no_active_record/app/000077500000000000000000000000001360670111200253605ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/no_active_record/app/models/000077500000000000000000000000001360670111200266435ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/no_active_record/app/models/in_memory/000077500000000000000000000000001360670111200306415ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/no_active_record/app/models/in_memory/model.rb000066400000000000000000000032111360670111200322630ustar00rootroot00000000000000raise "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-4.0.0.beta4/example_app_generator/no_active_record/lib/000077500000000000000000000000001360670111200253465ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/no_active_record/lib/rails/000077500000000000000000000000001360670111200264605ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/no_active_record/lib/rails/generators/000077500000000000000000000000001360670111200306315ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/no_active_record/lib/rails/generators/in_memory/000077500000000000000000000000001360670111200326275ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/no_active_record/lib/rails/generators/in_memory/model/000077500000000000000000000000001360670111200337275ustar00rootroot00000000000000model_generator.rb000066400000000000000000000014271360670111200373470ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/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/000077500000000000000000000000001360670111200356465ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/no_active_record/lib/rails/generators/in_memory/modelmodel.rb.erb000066400000000000000000000003321360670111200400400ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/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-4.0.0.beta4/example_app_generator/no_active_record/spec/000077500000000000000000000000001360670111200255325ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/no_active_record/spec/verify_no_active_record_spec.rb000066400000000000000000000002341360670111200337610ustar00rootroot00000000000000require 'rails_helper' RSpec.describe 'Example App' do it "does not have ActiveRecord defined" do expect(defined?(ActiveRecord)).not_to be end end rspec-rails-4.0.0.beta4/example_app_generator/run_specs.rb000066400000000000000000000011141360670111200236160ustar00rootroot00000000000000run('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-4.0.0.beta4/example_app_generator/spec/000077500000000000000000000000001360670111200222255ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/spec/__verify_fixture_load_order_spec.rb000066400000000000000000000003171360670111200313270ustar00rootroot00000000000000# 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-4.0.0.beta4/example_app_generator/spec/features/000077500000000000000000000000001360670111200240435ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/spec/features/model_mocks_integration_spec.rb000066400000000000000000000006521360670111200323040ustar00rootroot00000000000000require '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-4.0.0.beta4/example_app_generator/spec/support/000077500000000000000000000000001360670111200237415ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/example_app_generator/spec/support/default_preview_path000077500000000000000000000037041360670111200300740ustar00rootroot00000000000000#!/usr/bin/env ruby # Transparent helper to simply document code sections def require_file_stub(name) yield end ENV['RAILS_ENV'] ||= 'development' # Pick the frameworks you want: begin require "active_storage" require "active_storage/engine" rescue LoadError end 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. Bundler.require(*Rails.groups) module ExampleApp class Application < Rails::Application config.eager_load = false # 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 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-4.0.0.beta4/example_app_generator/spec/verify_active_record_spec.rb000066400000000000000000000002161360670111200277600ustar00rootroot00000000000000require 'rails_helper' RSpec.describe 'Example App' do it "has ActiveRecord defined" do expect(defined?(ActiveRecord)).to be end end rspec-rails-4.0.0.beta4/example_app_generator/spec/verify_custom_renderers_spec.rb000066400000000000000000000071131360670111200305350ustar00rootroot00000000000000require '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", :skip => Rails::VERSION::STRING.to_f >= 6.0 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, _source = nil| %("Dynamic template with path '#{_template.virtual_path}'") }, :virtual_path => path, :format => :html, :locals => [] ) end end end rspec-rails-4.0.0.beta4/example_app_generator/spec/verify_fixture_warning_spec.rb000066400000000000000000000027441360670111200303720ustar00rootroot00000000000000require '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-4.0.0.beta4/example_app_generator/spec/verify_mailer_preview_path_spec.rb000066400000000000000000000113721360670111200312020ustar00rootroot00000000000000require '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) ops << { :err => [:child, :out] } io = IO.popen(ops) # Necessary to ignore warnings from Rails code base out = io.readlines. reject { |line| line =~ /warning: circular argument reference/ }. reject { |line| line =~ /Gem::Specification#rubyforge_project=/ }. 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_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 skip "this spec fails singularly on JRuby due to weird env things" if RUBY_ENGINE == "jruby" 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 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-4.0.0.beta4/example_app_generator/travis_retry_bundle_install.sh000077500000000000000000000005661360670111200274550ustar00rootroot00000000000000#!/bin/bash set -e source FUNCTIONS_SCRIPT_FILE echo "Starting bundle install using shared bundle path" if is_mri; 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-4.0.0.beta4/features/000077500000000000000000000000001360670111200165505ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/.nav000066400000000000000000000020751360670111200173410ustar00rootroot00000000000000- 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-4.0.0.beta4/features/Generators.md000066400000000000000000000012501360670111200212010ustar00rootroot00000000000000RSpec 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-4.0.0.beta4/features/GettingStarted.md000066400000000000000000000044301360670111200220230ustar00rootroot00000000000000Install 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-4.0.0.beta4/features/README.md000066400000000000000000000025701360670111200200330ustar00rootroot00000000000000rspec-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](https://github.com/rspec/rspec-rails/issues) or a [pull request](https://github.com/rspec/rspec-rails). rspec-rails-4.0.0.beta4/features/RailsVersions.md000066400000000000000000000004331360670111200216750ustar00rootroot00000000000000 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-4.0.0.beta4/features/Transactions.md000066400000000000000000000054121360670111200215440ustar00rootroot00000000000000When 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(:example)` are rolled back Any data you create in a `before(:example)` 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(:example) 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(:context)` are _not_ rolled back `before(:context)` 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(:context)` hook: before(:context) do @widget = Widget.create! end after(:context) 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(:example)` hook. before(:context) do @widget = Widget.create! end before(:example) 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-4.0.0.beta4/features/backtrace_filtering.feature000066400000000000000000000023451360670111200241130ustar00rootroot00000000000000Feature: 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-4.0.0.beta4/features/channel_specs/000077500000000000000000000000001360670111200213555ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/channel_specs/channel_spec.feature000066400000000000000000000151431360670111200253600ustar00rootroot00000000000000@rails_post_6 Feature: channel spec Channel specs are marked by `:type => :channel` or if you have set `config.infer_spec_type_from_file_location!` by placing them in `spec/channels`. A channel spec is a thin wrapper for an `ActionCable::Channel::TestCase`, and includes all of the behavior and assertions that it provides, in addition to RSpec's own behavior and expectations. It also includes helpers from `ActionCable::Connection::TestCase` to make it possible to test connection behavior. Background: Given action cable testing is available And a file named "app/channels/chat_channel.rb" with: """ruby class ChatChannel < ApplicationCable::Channel def subscribed reject unless params[:room_id].present? end def speak(data) ActionCable.server.broadcast( "chat_#{params[:room_id]}", text: data['message'] ) end def echo(data) data.delete("action") transmit data end end """ Scenario: simple passing example Given a file named "spec/channels/chat_channel_spec.rb" with: """ruby require "rails_helper" RSpec.describe ChatChannel, :type => :channel do it "successfully subscribes" do subscribe room_id: 42 expect(subscription).to be_confirmed end end """ When I run `rspec spec/channels/chat_channel_spec.rb` Then the example should pass Scenario: verifying that subscription is rejected Given a file named "spec/channels/chat_channel_spec.rb" with: """ruby require "rails_helper" RSpec.describe ChatChannel, :type => :channel do it "rejects subscription" do subscribe room_id: nil expect(subscription).to be_rejected end end """ When I run `rspec spec/channels/chat_channel_spec.rb` Then the example should pass Scenario: performing actions and checking transmissions Given a file named "spec/channels/chat_channel_spec.rb" with: """ruby require "rails_helper" RSpec.describe ChatChannel, :type => :channel do it "successfully subscribes" do subscribe room_id: 42 perform :echo, foo: 'bar' expect(transmissions.last).to eq('foo' => 'bar') end end """ When I run `rspec spec/channels/chat_channel_spec.rb` Then the example should pass Scenario: successful connection with url params Given a file named "app/channels/application_cable/connection.rb" with: """ruby class ApplicationCable::Connection < ActionCable::Connection::Base identified_by :user_id def connect self.user_id = request.params[:user_id] reject_unauthorized_connection unless user_id.present? end end """ And a file named "spec/channels/connection_spec.rb" with: """ruby require "rails_helper" RSpec.describe ApplicationCable::Connection, :type => :channel do it "successfully connects" do connect "/cable?user_id=323" expect(connection.user_id).to eq "323" end end """ When I run `rspec spec/channels/connection_spec.rb` Then the example should pass Scenario: successful connection with cookies Given a file named "app/channels/application_cable/connection.rb" with: """ruby class ApplicationCable::Connection < ActionCable::Connection::Base identified_by :user_id def connect self.user_id = cookies.signed[:user_id] reject_unauthorized_connection unless user_id.present? end end """ And a file named "spec/channels/connection_spec.rb" with: """ruby require "rails_helper" RSpec.describe ApplicationCable::Connection, :type => :channel do it "successfully connects" do cookies.signed[:user_id] = "324" connect "/cable" expect(connection.user_id).to eq "324" end end """ When I run `rspec spec/channels/connection_spec.rb` Then the example should pass Scenario: successful connection with headers Given a file named "app/channels/application_cable/connection.rb" with: """ruby class ApplicationCable::Connection < ActionCable::Connection::Base identified_by :user_id def connect self.user_id = request.headers["x-user-id"] reject_unauthorized_connection unless user_id.present? end end """ And a file named "spec/channels/connection_spec.rb" with: """ruby require "rails_helper" RSpec.describe ApplicationCable::Connection, :type => :channel do it "successfully connects" do connect "/cable", headers: { "X-USER-ID" => "325" } expect(connection.user_id).to eq "325" end end """ When I run `rspec spec/channels/connection_spec.rb` Then the example should pass Scenario: rejected connection Given a file named "app/channels/application_cable/connection.rb" with: """ruby class ApplicationCable::Connection < ActionCable::Connection::Base identified_by :user_id def connect self.user_id = request.params[:user_id] reject_unauthorized_connection unless user_id.present? end end """ And a file named "spec/channels/connection_spec.rb" with: """ruby require "rails_helper" RSpec.describe ApplicationCable::Connection, :type => :channel do it "rejects connection" do expect { connect "/cable?user_id=" }.to have_rejected_connection end end """ When I run `rspec spec/channels/connection_spec.rb` Then the example should pass Scenario: disconnect connection Given a file named "app/channels/application_cable/connection.rb" with: """ruby class ApplicationCable::Connection < ActionCable::Connection::Base identified_by :user_id def connect self.user_id = request.params[:user_id] reject_unauthorized_connection unless user_id.present? end def disconnect $stdout.puts "User #{user_id} disconnected" end end """ And a file named "spec/channels/connection_spec.rb" with: """ruby require "rails_helper" RSpec.describe ApplicationCable::Connection, :type => :channel do it "disconnects" do connect "/cable?user_id=42" expect { disconnect }.to output(/User 42 disconnected/).to_stdout end end """ When I run `rspec spec/channels/connection_spec.rb` Then the example should pass rspec-rails-4.0.0.beta4/features/controller_specs/000077500000000000000000000000001360670111200221305ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/controller_specs/README.md000066400000000000000000000047121360670111200234130ustar00rootroot00000000000000Controller 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. ## Headers We encourage you to use [request specs](https://relishapp.com/rspec/rspec-rails/docs/request-specs/request-spec) if you want to set headers in your call. If you still want to use controller specs with custom http headers you can use `request.headers`: require "rails_helper" RSpec.describe TeamsController, type: :controller do describe "GET index" it "returns a 200" do request.headers["Authorization"] = "foo" get :show expect(response).to have_http_status(:ok) end end end rspec-rails-4.0.0.beta4/features/controller_specs/anonymous_controller.feature000066400000000000000000000405401360670111200300030ustar00rootroot00000000000000Feature: 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 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 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 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 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 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 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 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 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-4.0.0.beta4/features/controller_specs/bypass_rescue.feature000066400000000000000000000041221360670111200263530ustar00rootroot00000000000000Feature: 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-4.0.0.beta4/features/controller_specs/controller_spec.feature000066400000000000000000000066431360670111200267130ustar00rootroot00000000000000Feature: 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_6 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 @rails_post_6 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; charset=utf-8" 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; charset=utf-8" end end end """ When I run `rspec spec` Then the example should pass @rails_post_6 Scenario: setting a different media 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.media_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.media_type).to eq "application/json" end end end """ When I run `rspec spec` Then the example should pass rspec-rails-4.0.0.beta4/features/controller_specs/cookies.feature000066400000000000000000000020101360670111200251320ustar00rootroot00000000000000Feature: Cookies There are different ways to make assertions on cookies from controller specs, but we recommend using the `cookies` method as set out below. You can use strings or symbols to fetch or set your cookies because the `cookies` method supports indifferent access. Scenario: Testing cookie's value cleared in controller Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "rails_helper" RSpec.describe ApplicationController, :type => :controller do controller do def clear_cookie cookies.delete(:user_name) head :ok end end before do routes.draw { get "clear_cookie" => "anonymous#clear_cookie" } end it "clear cookie's value 'user_name'" do cookies[:user_name] = "Sam" get :clear_cookie expect(cookies[:user_name]).to eq nil end end """ When I run `rspec spec` Then the example should pass rspec-rails-4.0.0.beta4/features/controller_specs/engine_routes.feature000066400000000000000000000027031360670111200263550ustar00rootroot00000000000000Feature: 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. 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-4.0.0.beta4/features/controller_specs/isolation_from_views.feature000066400000000000000000000064641360670111200277600ustar00rootroot00000000000000Feature: 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 """ Given a file named "app/controllers/things_controller.rb" with: """ruby class ThingsController < ActionController::Base layout false def custom_action end end """ Given a file named "app/views/things/custom_action.html.erb" with: """ """ 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-4.0.0.beta4/features/controller_specs/render_views.feature000066400000000000000000000064141360670111200262060ustar00rootroot00000000000000Feature: 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-4.0.0.beta4/features/controller_specs/setting_request_headers.feature000066400000000000000000000025301360670111200304250ustar00rootroot00000000000000Feature: Setting request headers We recommend you to switch to request specs instead of controller specs if you want to set headers in your call. If you still want to set headers in controller specs, you can use `request.headers` as mentioned bellow. Scenario: Setting a header value in a controller spec Given a file named "spec/controllers/application_controller_spec.rb" with: """ruby require "rails_helper" RSpec.describe ApplicationController, type: :controller do controller do def show if request.headers["Authorization"] == "foo" head :ok else head :forbidden end end end before do routes.draw { get "show" => "anonymous#show" } end context "valid Authorization header" do it "returns a 200" do request.headers["Authorization"] = "foo" get :show expect(response).to have_http_status(:ok) end end context "invalid Authorization header" do it "returns a 403" do request.headers["Authorization"] = "bar" get :show expect(response).to have_http_status(:forbidden) end end end """ When I run `rspec spec` Then the example should pass rspec-rails-4.0.0.beta4/features/directory_structure.feature000066400000000000000000000155201360670111200242540ustar00rootroot00000000000000Feature: 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-4.0.0.beta4/features/feature_specs/000077500000000000000000000000001360670111200214005ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/feature_specs/feature_spec.feature000066400000000000000000000060321360670111200254230ustar00rootroot00000000000000Feature: 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](https://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](https://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 (https://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-4.0.0.beta4/features/file_fixture.feature000066400000000000000000000020331360670111200226100ustar00rootroot00000000000000Feature: 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 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-4.0.0.beta4/features/helper_specs/000077500000000000000000000000001360670111200212245ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/helper_specs/helper_spec.feature000066400000000000000000000074131360670111200250770ustar00rootroot00000000000000Feature: 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-4.0.0.beta4/features/job_specs/000077500000000000000000000000001360670111200205175ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/job_specs/job_spec.feature000066400000000000000000000116171360670111200236660ustar00rootroot00000000000000Feature: 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), [`have_enqueued_job`](../matchers/have-enqueued-job-matcher), [`have_been_performed`](../matchers/have-been-performed-matcher), and [`have_performed_job`](../matchers/have-performed-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 no wait 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(queue: "low").perform_later('backup') }.to have_enqueued_job.with('backup').on_queue("low").at(:no_wait) 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-4.0.0.beta4/features/mailer_specs/000077500000000000000000000000001360670111200212165ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/mailer_specs/README.md000066400000000000000000000015001360670111200224710ustar00rootroot00000000000000By 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-4.0.0.beta4/features/mailer_specs/mailer_spec.feature000066400000000000000000000013271360670111200250610ustar00rootroot00000000000000Feature: mailer spec 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 rspec-rails-4.0.0.beta4/features/mailer_specs/url_helpers.feature000066400000000000000000000026041360670111200251210ustar00rootroot00000000000000Feature: 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`. 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 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 rspec-rails-4.0.0.beta4/features/matchers/000077500000000000000000000000001360670111200203565ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/matchers/README.md000066400000000000000000000007371360670111200216440ustar00rootroot00000000000000rspec-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-4.0.0.beta4/features/matchers/have_been_enqueued_matcher.feature000066400000000000000000000056051360670111200272530ustar00rootroot00000000000000Feature: 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 enqueued with no wait 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.at(:no_wait) 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-4.0.0.beta4/features/matchers/have_been_performed_matcher.feature000066400000000000000000000053311360670111200274170ustar00rootroot00000000000000Feature: have_been_performed matcher The `have_been_performed` matcher is used to check if given ActiveJob job was performed. 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 performed job" do ActiveJob::Base.queue_adapter = :test ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true UploadBackupsJob.perform_later expect(UploadBackupsJob).to have_been_performed 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 performed job" do ActiveJob::Base.queue_adapter = :test ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true UploadBackupsJob.perform_later("users-backup.txt", "products-backup.txt") expect(UploadBackupsJob).to( have_been_performed.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 performed time Given a file named "spec/jobs/upload_backups_job_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob do it "matches with performed job" do ActiveJob::Base.queue_adapter = :test ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = true UploadBackupsJob.set(:wait_until => Date.tomorrow.noon).perform_later expect(UploadBackupsJob).to have_been_performed.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 performed job" do ActiveJob::Base.queue_adapter = :test ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true UploadBackupsJob.perform_later expect(UploadBackupsJob).to have_been_performed.on_queue("default") end end """ When I run `rspec spec/jobs/upload_backups_job_spec.rb` Then the examples should all pass rspec-rails-4.0.0.beta4/features/matchers/have_broadcasted_matcher.feature000066400000000000000000000105161360670111200267170ustar00rootroot00000000000000@rails_post_6 Feature: have_broadcasted matcher The `have_broadcasted_to` (also aliased as `broadcast_to`) matcher is used to check if a message has been broadcasted to a given stream. Background: Given action cable testing is available Scenario: Checking stream name Given a file named "spec/models/broadcaster_spec.rb" with: """ruby require "rails_helper" RSpec.describe "broadcasting" do it "matches with stream name" do expect { ActionCable.server.broadcast( "notifications", text: 'Hello!' ) }.to have_broadcasted_to("notifications") end end """ When I run `rspec spec/models/broadcaster_spec.rb` Then the examples should all pass Scenario: Checking passed message to stream Given a file named "spec/models/broadcaster_spec.rb" with: """ruby require "rails_helper" RSpec.describe "broadcasting" do it "matches with message" do expect { ActionCable.server.broadcast( "notifications", text: 'Hello!' ) }.to have_broadcasted_to("notifications").with(text: 'Hello!') end end """ When I run `rspec spec/models/broadcaster_spec.rb` Then the examples should all pass Scenario: Checking that message passed to stream matches Given a file named "spec/models/broadcaster_spec.rb" with: """ruby require "rails_helper" RSpec.describe "broadcasting" do it "matches with message" do expect { ActionCable.server.broadcast( "notifications", text: 'Hello!', user_id: 12 ) }.to have_broadcasted_to("notifications").with(a_hash_including(text: 'Hello!')) end end """ When I run `rspec spec/models/broadcaster_spec.rb` Then the examples should all pass Scenario: Checking passed message with block Given a file named "spec/models/broadcaster_spec.rb" with: """ruby require "rails_helper" RSpec.describe "broadcasting" do it "matches with message" do expect { ActionCable.server.broadcast( "notifications", text: 'Hello!', user_id: 12 ) }.to have_broadcasted_to("notifications").with { |data| expect(data['user_id']).to eq 12 } end end """ When I run `rspec spec/models/broadcaster_spec.rb` Then the examples should all pass Scenario: Using alias method Given a file named "spec/models/broadcaster_spec.rb" with: """ruby require "rails_helper" RSpec.describe "broadcasting" do it "matches with stream name" do expect { ActionCable.server.broadcast( "notifications", text: 'Hello!' ) }.to broadcast_to("notifications") end end """ When I run `rspec spec/models/broadcaster_spec.rb` Then the examples should all pass Scenario: Checking broadcast to a record Given a file named "spec/channels/chat_channel_spec.rb" with: """ruby require "rails_helper" RSpec.describe ChatChannel, type: :channel do it "successfully subscribes" do user = User.new(42) expect { ChatChannel.broadcast_to(user, text: 'Hi') }.to have_broadcasted_to(user) end end """ And a file named "app/models/user.rb" with: """ruby class User < Struct.new(:name) def to_gid_param name end end """ When I run `rspec spec/channels/chat_channel_spec.rb` Then the example should pass Scenario: Checking broadcast to a record in non-channel spec Given a file named "spec/models/broadcaster_spec.rb" with: """ruby require "rails_helper" RSpec.describe "broadcasting" do it "matches with stream name" do user = User.new(42) expect { ChatChannel.broadcast_to(user, text: 'Hi') }.to broadcast_to(ChatChannel.broadcasting_for(user)) end end """ And a file named "app/models/user.rb" with: """ruby class User < Struct.new(:name) def to_gid_param name end end """ When I run `rspec spec/models/broadcaster_spec.rb` Then the example should pass rspec-rails-4.0.0.beta4/features/matchers/have_enqueued_job_matcher.feature000066400000000000000000000101241360670111200271040ustar00rootroot00000000000000Feature: 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 passed arguments to job, using a block 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('backups.txt', rand(100), 'uninteresting third argument') }.to have_enqueued_job.with { |file_name, seed| expect(file_name).to eq 'backups.txt' expect(seed).to be < 100 } 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 enqueued with no wait 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.at(:no_wait) 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-4.0.0.beta4/features/matchers/have_enqueued_mail_matcher.feature000066400000000000000000000024661360670111200272660ustar00rootroot00000000000000Feature: have_enqueued_mail matcher The `have_enqueued_mail` (also aliased as `enqueue_mail`) matcher is used to check if given mailer was enqueued. Background: Given active job is available Scenario: Checking mailer class and method name Given a file named "spec/mailers/user_mailer_spec.rb" with: """ruby require "rails_helper" RSpec.describe NotificationsMailer do it "matches with enqueued mailer" do ActiveJob::Base.queue_adapter = :test expect { NotificationsMailer.signup.deliver_later }.to have_enqueued_mail(NotificationsMailer, :signup) end end """ When I run `rspec spec/mailers/user_mailer_spec.rb` Then the examples should all pass Scenario: Checking mailer enqueued time Given a file named "spec/mailers/user_mailer_spec.rb" with: """ruby require "rails_helper" RSpec.describe NotificationsMailer do it "matches with enqueued mailer" do ActiveJob::Base.queue_adapter = :test expect { NotificationsMailer.signup.deliver_later(wait_until: Date.tomorrow.noon) }.to have_enqueued_mail.at(Date.tomorrow.noon) end end """ When I run `rspec spec/mailers/user_mailer_spec.rb` Then the examples should all pass rspec-rails-4.0.0.beta4/features/matchers/have_http_status_matcher.feature000066400000000000000000000102271360670111200270250ustar00rootroot00000000000000Feature: `have_http_status` matcher The `have_http_status` matcher is used to specify that a response returns a desired status code. It accepts one argument in any of the following formats: * numeric code * status name as defined in `Rack::Utils::SYMBOL_TO_STATUS_CODE` * generic status type (`:success`, `:missing`, `:redirect`, or `:error`) 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 status 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 status name 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 symbolic generic status type 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 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-4.0.0.beta4/features/matchers/have_performed_job_matcher.feature000066400000000000000000000064521360670111200272650ustar00rootroot00000000000000Feature: have_performed_job matcher The `have_performed_job` (also aliased as `perform_job`) matcher is used to check if given ActiveJob job was performed. 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 performed job" do ActiveJob::Base.queue_adapter = :test ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true expect { UploadBackupsJob.perform_later }.to have_performed_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 performed job" do ActiveJob::Base.queue_adapter = :test ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true expect { UploadBackupsJob.perform_later("users-backup.txt", "products-backup.txt") }.to have_performed_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 performed time Given a file named "spec/jobs/upload_backups_job_spec.rb" with: """ruby require "rails_helper" RSpec.describe UploadBackupsJob do it "matches with performed job" do ActiveJob::Base.queue_adapter = :test ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = true expect { UploadBackupsJob.set(:wait_until => Date.tomorrow.noon).perform_later }.to have_performed_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 performed job" do ActiveJob::Base.queue_adapter = :test ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true expect { UploadBackupsJob.perform_later }.to have_performed_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 performed job" do ActiveJob::Base.queue_adapter = :test ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true expect { UploadBackupsJob.perform_later }.to perform_job(UploadBackupsJob) end end """ When I run `rspec spec/jobs/upload_backups_job_spec.rb` Then the examples should all pass rspec-rails-4.0.0.beta4/features/matchers/have_stream_from_matcher.feature000066400000000000000000000060251360670111200267620ustar00rootroot00000000000000@rails_post_6 Feature: have_stream_from matcher The `have_stream_from` matcher is used to check if a channel has been subscribed to a given stream specified as a String. If you use `stream_for` in you channel to subscribe to a model, use `have_stream_for` matcher instead. The `have_no_streams` matcher is used to check if a channe hasn't been subscribed to any stream. It is available only in channel specs. Background: Given action cable testing is available And a file named "app/channels/chat_channel.rb" with: """ruby class ChatChannel < ApplicationCable::Channel def subscribed reject unless params[:room_id].present? stream_from "chat_#{params[:room_id]}" end def leave stop_all_streams end end """ Scenario: subscribing with params and checking streams Given a file named "spec/channels/chat_channel_spec.rb" with: """ruby require "rails_helper" RSpec.describe ChatChannel, :type => :channel do it "successfully subscribes" do subscribe room_id: 42 expect(subscription).to be_confirmed expect(subscription).to have_stream_from("chat_42") end end """ When I run `rspec spec/channels/chat_channel_spec.rb` Then the example should pass Scenario: stopping all streams Given a file named "spec/channels/chat_channel_spec.rb" with: """ruby require "rails_helper" RSpec.describe ChatChannel, :type => :channel do it "successfully subscribes" do subscribe(room_id: 42) expect(subscription).to have_stream_from("chat_42") perform :leave expect(subscription).not_to have_streams end end """ When I run `rspec spec/channels/chat_channel_spec.rb` Then the example should pass Scenario: subscribing and checking streams for models Given a file named "app/channels/notifications_channel.rb" with: """ruby class NotificationsChannel < ApplicationCable::Channel def subscribed stream_for current_user end end """ And a file named "app/channels/application_cable/connection.rb" with: """ruby class ApplicationCable::Connection < ActionCable::Connection::Base identified_by :current_user end """ And a file named "app/models/user.rb" with: """ruby class User < Struct.new(:name) def to_gid_param name end end """ And a file named "spec/channels/user_channel_spec.rb" with: """ruby require "rails_helper" RSpec.describe NotificationsChannel, :type => :channel do it "successfully subscribes to user's stream" do stub_connection current_user: User.new(42) subscribe expect(subscription).to be_confirmed expect(subscription).to have_stream_for(User.new(42)) end end """ When I run `rspec spec/channels/user_channel_spec.rb` Then the example should pass rspec-rails-4.0.0.beta4/features/matchers/new_record_matcher.feature000066400000000000000000000022141360670111200255640ustar00rootroot00000000000000Feature: 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-4.0.0.beta4/features/matchers/redirect_to_matcher.feature000066400000000000000000000026401360670111200257430ustar00rootroot00000000000000Feature: 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`](https://api.rubyonrails.org/classes/ActionDispatch/Assertions/ResponseAssertions.html#method-i-assert_redirected_to). It is available in controller specs (spec/controllers) and request specs (spec/requests). Scenario: redirect_to with four possible options Given a file named "spec/controllers/widgets_controller_spec.rb" with: """ruby require "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-4.0.0.beta4/features/matchers/relation_match_array.feature000066400000000000000000000013571360670111200261300ustar00rootroot00000000000000Feature: 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 } } subject { Widget.all } 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-4.0.0.beta4/features/matchers/render_template_matcher.feature000066400000000000000000000050471360670111200266160ustar00rootroot00000000000000Feature: render_template matcher The `render_template` matcher is used to specify that a request renders a given template or layout. It delegates to [`assert_template`](https://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: specify that a request renders a given layout 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 application layout" do expect(subject).to render_template("layouts/application") end it "does not render a different layout" do expect(subject).to_not render_template("layouts/admin") 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-4.0.0.beta4/features/model_specs/000077500000000000000000000000001360670111200210455ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/model_specs/README.md000066400000000000000000000014101360670111200223200ustar00rootroot00000000000000Model 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-4.0.0.beta4/features/model_specs/transactional_examples.feature000066400000000000000000000054541360670111200271720ustar00rootroot00000000000000Feature: 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-4.0.0.beta4/features/model_specs/verified_doubles.feature000066400000000000000000000010761360670111200257400ustar00rootroot00000000000000Feature: 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-4.0.0.beta4/features/request_specs/000077500000000000000000000000001360670111200214355ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/request_specs/request_spec.feature000066400000000000000000000076531360670111200255270ustar00rootroot00000000000000Feature: 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](https://github.com/jnicklas/capybara) is no longer supported in request specs as of Capybara 2.0.0. The recommended way to use Capybara is with [feature specs](../feature-specs/feature-spec). Scenario: specify managing a Widget with Rails integration methods Given a file named "spec/requests/widget_management_spec.rb" with: """ruby require "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 @rails_pre_6 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" } 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_post_6 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" } post "/widgets", :params => { :widget => {:name => "My Widget"} }, :headers => headers expect(response.content_type).to eq("application/json; charset=utf-8") expect(response).to have_http_status(:created) end end """ When I run `rspec spec/requests/widget_management_spec.rb` Then the example should pass 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-4.0.0.beta4/features/routing_specs/000077500000000000000000000000001360670111200214345ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/routing_specs/README.md000066400000000000000000000012301360670111200227070ustar00rootroot00000000000000Routing 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-4.0.0.beta4/features/routing_specs/be_routable_matcher.feature000066400000000000000000000051141360670111200270000ustar00rootroot00000000000000Feature: 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-4.0.0.beta4/features/routing_specs/engine_routes.feature000066400000000000000000000020141360670111200256540ustar00rootroot00000000000000Feature: engine routes Routing specs can specify the routeset that will be used for the example group. This is most useful when testing Rails engines. 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-4.0.0.beta4/features/routing_specs/named_routes.feature000066400000000000000000000010261360670111200254750ustar00rootroot00000000000000Feature: 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-4.0.0.beta4/features/routing_specs/route_to_matcher.feature000066400000000000000000000055701360670111200263630ustar00rootroot00000000000000Feature: 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-4.0.0.beta4/features/step_definitions/000077500000000000000000000000001360670111200221165ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/step_definitions/additional_cli_steps.rb000066400000000000000000000015301360670111200266170ustar00rootroot00000000000000begin require "active_job" rescue LoadError # rubocop:disable Lint/SuppressedException end begin require "action_cable" rescue LoadError # rubocop:disable Lint/SuppressedException 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 /action cable testing is available/ do if !RSpec::Rails::FeatureCheck.has_action_cable_testing? pending "Action Cable testing is not available" end end rspec-rails-4.0.0.beta4/features/support/000077500000000000000000000000001360670111200202645ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/support/capybara.rb000066400000000000000000000001161360670111200223710ustar00rootroot00000000000000Around "@capybara" do |scenario, block| require 'capybara' block.call end rspec-rails-4.0.0.beta4/features/support/env.rb000066400000000000000000000033461360670111200214070ustar00rootroot00000000000000require 'aruba/cucumber' require 'fileutils' module ArubaExt def run_command(cmd, timeout = nil) exec_cmd = cmd =~ /^rspec/ ? "bin/#{cmd}" : cmd unset_bundler_env_vars # Ensure the correct Gemfile and binstubs are found in_current_directory do with_unbundled_env do super(exec_cmd, timeout) end end end def unset_bundler_env_vars empty_env = with_environment { with_unbundled_env { ENV.to_h } } aruba_env = aruba.environment.to_h (aruba_env.keys - empty_env.keys).each do |key| delete_environment_variable key end empty_env.each do |k, v| set_environment_variable k, v end end def with_unbundled_env if Bundler.respond_to?(:with_unbundled_env) Bundler.with_unbundled_env { yield } else Bundler.with_clean_env { yield } end end end World(ArubaExt) Aruba.configure do |config| config.exit_timeout = 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-4.0.0.beta4/features/support/rails_versions.rb000066400000000000000000000000001360670111200236410ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/support/rubinius.rb000066400000000000000000000003411360670111200224470ustar00rootroot00000000000000# 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-4.0.0.beta4/features/system_specs/000077500000000000000000000000001360670111200212715ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/system_specs/system_specs.feature000066400000000000000000000037301360670111200253720ustar00rootroot00000000000000Feature: System spec System specs are RSpec's wrapper around Rails' own [system tests](https://guides.rubyonrails.org/testing.html#system-testing). > System tests allow you to test user interactions with your application, > running tests in either a real or a headless browser. System tests use > Capybara under the hood. > > By default, system tests are run with the Selenium driver, using the > Chrome browser, and a screen size of 1400x1400. The next section explains > how to change the default settings. System specs are marked by setting type to :system, e.g. `:type => :system`. The Capybara gem is automatically required, and Rails includes it in generated application Gemfiles. Configure a webserver (e.g. `Capybara.server = :webrick`) before attempting to use system specs. 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 specs run in a transaction. So unlike feature specs with javascript, you do not need [DatabaseCleaner](https://github.com/DatabaseCleaner/database_cleaner). @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-4.0.0.beta4/features/upgrade/000077500000000000000000000000001360670111200201775ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/upgrade/README.md000066400000000000000000000147471360670111200214730ustar00rootroot00000000000000# 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-4.0.0.beta4/features/upgrade/from_1x_to_2x.md000066400000000000000000000074551360670111200232220ustar00rootroot00000000000000# 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-4.0.0.beta4/features/view_specs/000077500000000000000000000000001360670111200207175ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/features/view_specs/inferred_controller_path.feature000066400000000000000000000025131360670111200273520ustar00rootroot00000000000000Feature: 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-4.0.0.beta4/features/view_specs/stub_template.feature000066400000000000000000000031101360670111200251370ustar00rootroot00000000000000Feature: 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-4.0.0.beta4/features/view_specs/view_spec.feature000066400000000000000000000205311360670111200242610ustar00rootroot00000000000000Feature: view spec View specs are marked by `:type => :view` or if you have set `config.infer_spec_type_from_file_location!` by placing them in `spec/views`. Use them to test the content of view templates without invoking a specific controller. They generally follow three steps: ```ruby assign(:widget, Widget.new) # sets @widget = Widget.new in the view template render expect(rendered).to match(/text/) ``` 1. Use the `assign` method to set instance variables in the view. 2. Use the `render` method to render the view. 3. Set expectations against the resulting rendered template. 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 render templates in layouts Given a file named "spec/views/widgets/widget.html.erb_spec.rb" with: """ruby require "rails_helper" RSpec.describe "rendering the widget template" do context "with the inventory layout" do it "displays the widget" do assign(:widget, Widget.create!(:name => "slicer")) render :template => "widgets/widget.html.erb", :layout => "layouts/inventory" expect(rendered).to match /slicer/ end end end """ And a file named "app/views/widgets/widget.html.erb" with: """

<%= @widget.name %>

""" And a file named "app/views/layouts/inventory.html.erb" with: """ <%= yield %> """ 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 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-4.0.0.beta4/lib/000077500000000000000000000000001360670111200155005ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/000077500000000000000000000000001360670111200176515ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec.rb000066400000000000000000000016161360670111200213160ustar00rootroot00000000000000require '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 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-4.0.0.beta4/lib/generators/rspec/000077500000000000000000000000001360670111200207655ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/channel/000077500000000000000000000000001360670111200223755ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/channel/channel_generator.rb000066400000000000000000000004271360670111200264030ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators # @private class ChannelGenerator < Base def create_channel_spec template 'channel_spec.rb.erb', File.join('spec/channels', class_path, "#{file_name}_channel_spec.rb") end end end end rspec-rails-4.0.0.beta4/lib/generators/rspec/channel/templates/000077500000000000000000000000001360670111200243735ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/channel/templates/channel_spec.rb.erb000066400000000000000000000003071360670111200301110ustar00rootroot00000000000000require 'rails_helper' <% module_namespacing do -%> RSpec.describe <%= class_name %>Channel, <%= type_metatag(:channel) %> do pending "add some examples to (or delete) #{__FILE__}" end <% end -%> rspec-rails-4.0.0.beta4/lib/generators/rspec/controller/000077500000000000000000000000001360670111200231505ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/controller/controller_generator.rb000066400000000000000000000034261360670111200277330ustar00rootroot00000000000000require '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 :request_specs, type: :boolean, default: true, desc: "Generate request specs" class_option :controller_specs, type: :boolean, default: false, desc: "Generate controller specs" class_option :view_specs, type: :boolean, default: true, desc: "Generate view specs" class_option :routing_specs, type: :boolean, default: false, desc: "Generate routing specs" def generate_request_spec return unless options[:request_specs] template 'request_spec.rb', File.join('spec/requests', class_path, "#{file_name}_request_spec.rb") end 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 def generate_routing_spec return if actions.empty? return unless options[:routing_specs] template 'routing_spec.rb', File.join('spec/routing', class_path, "#{file_name}_routing_spec.rb") end end end end rspec-rails-4.0.0.beta4/lib/generators/rspec/controller/templates/000077500000000000000000000000001360670111200251465ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/controller/templates/controller_spec.rb000066400000000000000000000005361360670111200306740ustar00rootroot00000000000000require '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-4.0.0.beta4/lib/generators/rspec/controller/templates/request_spec.rb000066400000000000000000000006611360670111200302000ustar00rootroot00000000000000require 'rails_helper' RSpec.describe "<%= class_name.pluralize %>", <%= type_metatag(:request) %> do <% namespaced_path = regular_class_path.join('/') %> <% for action in actions -%> describe "GET /<%= action %>" do it "returns http success" do get "<%= "/#{namespaced_path}" if namespaced_path != '' %>/<%= file_name %>/<%= action %>" expect(response).to have_http_status(:success) end end <% end -%> end rspec-rails-4.0.0.beta4/lib/generators/rspec/controller/templates/routing_spec.rb000066400000000000000000000006021360670111200301720ustar00rootroot00000000000000require 'rails_helper' <% module_namespacing do -%> RSpec.describe '<%= class_name %>Controller', <%= type_metatag(:routing) %> do describe 'routing' do <% for action in actions -%> it 'routes to #<%= action %>' do expect(get: "/<%= class_name.underscore %>/<%= action %>").to route_to("<%= class_name.underscore %>#<%= action %>") end <% end -%> end end <% end -%> rspec-rails-4.0.0.beta4/lib/generators/rspec/controller/templates/view_spec.rb000066400000000000000000000003131360670111200274540ustar00rootroot00000000000000require '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-4.0.0.beta4/lib/generators/rspec/feature/000077500000000000000000000000001360670111200224205ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/feature/feature_generator.rb000066400000000000000000000014221360670111200264450ustar00rootroot00000000000000require '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] "#{file_name.singularize}_spec.rb" else "#{file_name}_spec.rb" end end end end end rspec-rails-4.0.0.beta4/lib/generators/rspec/feature/templates/000077500000000000000000000000001360670111200244165ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/feature/templates/feature_singular_spec.rb000066400000000000000000000002431360670111200313130ustar00rootroot00000000000000require 'rails_helper' RSpec.feature "<%= class_name.singularize %>", <%= type_metatag(:feature) %> do pending "add some scenarios (or delete) #{__FILE__}" end rspec-rails-4.0.0.beta4/lib/generators/rspec/feature/templates/feature_spec.rb000066400000000000000000000002411360670111200274050ustar00rootroot00000000000000require 'rails_helper' RSpec.feature "<%= class_name.pluralize %>", <%= type_metatag(:feature) %> do pending "add some scenarios (or delete) #{__FILE__}" end rspec-rails-4.0.0.beta4/lib/generators/rspec/generators/000077500000000000000000000000001360670111200231365ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/generators/generator_generator.rb000066400000000000000000000010411360670111200275130ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators # @private class GeneratorsGenerator < Base class_option :generator_specs, type: :boolean, default: false, desc: "Generate generator specs" def generate_generator_spec return unless options[:generator_specs] template template_name, File.join('spec/generator', class_path, filename) end def template_name 'generator_spec.rb' end def filename "#{table_name}_generator_spec.rb" end end end end rspec-rails-4.0.0.beta4/lib/generators/rspec/generators/templates/000077500000000000000000000000001360670111200251345ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/generators/templates/generator_spec.rb000066400000000000000000000002451360670111200304620ustar00rootroot00000000000000require 'rails_helper' RSpec.describe "<%= class_name.pluralize %>", <%= type_metatag(:generator) %> do pending "add some scenarios (or delete) #{__FILE__}" end rspec-rails-4.0.0.beta4/lib/generators/rspec/helper/000077500000000000000000000000001360670111200222445ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/helper/helper_generator.rb000066400000000000000000000005771360670111200261270ustar00rootroot00000000000000require '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-4.0.0.beta4/lib/generators/rspec/helper/templates/000077500000000000000000000000001360670111200242425ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/helper/templates/helper_spec.rb000066400000000000000000000010111360670111200270510ustar00rootroot00000000000000require '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-4.0.0.beta4/lib/generators/rspec/install/000077500000000000000000000000001360670111200224335ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/install/install_generator.rb000066400000000000000000000032311360670111200264730ustar00rootroot00000000000000require "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 < # Checks for pending migrations and applies them before tests are run. # If you are not using ActiveRecord, you can remove these lines. begin ActiveRecord::Migration.maintain_test_schema! rescue ActiveRecord::PendingMigrationError => e puts e.to_s.strip exit 1 end <% 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-4.0.0.beta4/lib/generators/rspec/integration/000077500000000000000000000000001360670111200233105ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/integration/integration_generator.rb000066400000000000000000000011361360670111200302270ustar00rootroot00000000000000require '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', "#{name.underscore.pluralize}_spec.rb") end end end end rspec-rails-4.0.0.beta4/lib/generators/rspec/integration/templates/000077500000000000000000000000001360670111200253065ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/integration/templates/request_spec.rb000066400000000000000000000004611360670111200303360ustar00rootroot00000000000000require 'rails_helper' RSpec.describe "<%= class_name.pluralize %>", <%= type_metatag(:request) %> do describe "GET /<%= name.underscore.pluralize %>" 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-4.0.0.beta4/lib/generators/rspec/job/000077500000000000000000000000001360670111200215375ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/job/job_generator.rb000066400000000000000000000004031360670111200247010ustar00rootroot00000000000000require '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-4.0.0.beta4/lib/generators/rspec/job/templates/000077500000000000000000000000001360670111200235355ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/job/templates/job_spec.rb.erb000066400000000000000000000002771360670111200264230ustar00rootroot00000000000000require '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-4.0.0.beta4/lib/generators/rspec/mailbox/000077500000000000000000000000001360670111200224205ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/mailbox/mailbox_generator.rb000066400000000000000000000004631360670111200264510ustar00rootroot00000000000000require 'generators/rspec' module Rspec module Generators # @private class MailboxGenerator < Base def create_mailbox_spec template('mailbox_spec.rb.erb', File.join('spec/mailboxes', class_path, "#{file_name}_mailbox_spec.rb") ) end end end end rspec-rails-4.0.0.beta4/lib/generators/rspec/mailbox/templates/000077500000000000000000000000001360670111200244165ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/mailbox/templates/mailbox_spec.rb.erb000066400000000000000000000003071360670111200301570ustar00rootroot00000000000000require 'rails_helper' <% module_namespacing do -%> RSpec.describe <%= class_name %>Mailbox, <%= type_metatag(:mailbox) %> do pending "add some examples to (or delete) #{__FILE__}" end <% end -%> rspec-rails-4.0.0.beta4/lib/generators/rspec/mailer/000077500000000000000000000000001360670111200222365ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/mailer/mailer_generator.rb000066400000000000000000000014661360670111200261110ustar00rootroot00000000000000require '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-4.0.0.beta4/lib/generators/rspec/mailer/templates/000077500000000000000000000000001360670111200242345ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/mailer/templates/fixture000066400000000000000000000001101360670111200256350ustar00rootroot00000000000000<%= class_name %>#<%= @action %> Hi, find me in app/views/<%= @path %> rspec-rails-4.0.0.beta4/lib/generators/rspec/mailer/templates/mailer_spec.rb000066400000000000000000000014251360670111200270460ustar00rootroot00000000000000require "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-4.0.0.beta4/lib/generators/rspec/mailer/templates/preview.rb000066400000000000000000000006751360670111200262520ustar00rootroot00000000000000<% 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 %> <%= Rails.version.to_f >= 5.0 ? class_name.sub(/(Mailer)?$/, 'Mailer') : class_name %>.<%= action %> end <% end -%> end <% end -%> rspec-rails-4.0.0.beta4/lib/generators/rspec/model/000077500000000000000000000000001360670111200220655ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/model/model_generator.rb000066400000000000000000000016151360670111200255630ustar00rootroot00000000000000require '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', class_path, "#{(pluralize_table_names? ? plural_file_name : file_name)}.yml") end private def missing_fixture_replacement? options[:fixture] && options[:fixture_replacement].nil? end end end end rspec-rails-4.0.0.beta4/lib/generators/rspec/model/templates/000077500000000000000000000000001360670111200240635ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/model/templates/fixtures.yml000066400000000000000000000006211360670111200264560ustar00rootroot00000000000000# Read about fixtures at https://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-4.0.0.beta4/lib/generators/rspec/model/templates/model_spec.rb000066400000000000000000000002761360670111200265270ustar00rootroot00000000000000require '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-4.0.0.beta4/lib/generators/rspec/request/000077500000000000000000000000001360670111200224555ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/request/request_generator.rb000066400000000000000000000003761360670111200265460ustar00rootroot00000000000000require 'generators/rspec/integration/integration_generator' module Rspec module Generators # @private class RequestGenerator < IntegrationGenerator source_paths << File.expand_path('../integration/templates', __dir__) end end end rspec-rails-4.0.0.beta4/lib/generators/rspec/scaffold/000077500000000000000000000000001360670111200225465ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/scaffold/scaffold_generator.rb000066400000000000000000000072251360670111200267300ustar00rootroot00000000000000require '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', __dir__) 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 return file_name if ns_parts.empty? "#{ns_prefix.map(&:underscore).join('/')}_#{ns_suffix.singularize.underscore}" end # support for namespaced-resources def ns_table_name return table_name if ns_parts.empty? "#{ns_prefix.map(&:underscore).join('/')}/#{ns_suffix.tableize}" end def ns_parts @ns_parts ||= begin parts = generator_args[0].split(/\/|::/) parts.size > 1 ? parts : [] end end def ns_prefix @ns_prefix ||= ns_parts[0..-2] end def ns_suffix @ns_suffix ||= ns_parts[-1] 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-4.0.0.beta4/lib/generators/rspec/scaffold/templates/000077500000000000000000000000001360670111200245445ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/scaffold/templates/api_controller_spec.rb000066400000000000000000000124101360670111200311150ustar00rootroot00000000000000require '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 get :index, params: {}, session: valid_session expect(response).to be_successful end end <% end -%> describe "GET #show" do it "returns a success response" do <%= file_name %> = <%= class_name %>.create! valid_attributes get :show, params: {id: <%= file_name %>.to_param}, session: valid_session expect(response).to be_successful end end describe "POST #create" do context "with valid params" do it "creates a new <%= class_name %>" do expect { post :create, params: {<%= ns_file_name %>: valid_attributes}, session: valid_session }.to change(<%= class_name %>, :count).by(1) end it "renders a JSON response with the new <%= ns_file_name %>" do post :create, params: {<%= ns_file_name %>: valid_attributes}, session: valid_session 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 post :create, params: {<%= ns_file_name %>: invalid_attributes}, session: valid_session 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 put :update, params: {id: <%= file_name %>.to_param, <%= ns_file_name %>: new_attributes}, session: valid_session <%= 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 put :update, params: {id: <%= file_name %>.to_param, <%= ns_file_name %>: valid_attributes}, session: valid_session 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 put :update, params: {id: <%= file_name %>.to_param, <%= ns_file_name %>: invalid_attributes}, session: valid_session 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 { delete :destroy, params: {id: <%= file_name %>.to_param}, session: valid_session }.to change(<%= class_name %>, :count).by(-1) end end end <% end -%> rspec-rails-4.0.0.beta4/lib/generators/rspec/scaffold/templates/controller_spec.rb000066400000000000000000000162501360670111200302720ustar00rootroot00000000000000require '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 <%= 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_successful 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_successful 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_successful 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_successful 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_successful 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_successful 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-4.0.0.beta4/lib/generators/rspec/scaffold/templates/edit_spec.rb000066400000000000000000000023331360670111200270310ustar00rootroot00000000000000require '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-4.0.0.beta4/lib/generators/rspec/scaffold/templates/index_spec.rb000066400000000000000000000016601360670111200272150ustar00rootroot00000000000000require '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-4.0.0.beta4/lib/generators/rspec/scaffold/templates/new_spec.rb000066400000000000000000000022501360670111200266730ustar00rootroot00000000000000require '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-4.0.0.beta4/lib/generators/rspec/scaffold/templates/routing_spec.rb000066400000000000000000000025471360670111200276020ustar00rootroot00000000000000require "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 it "routes to #update via PATCH" do expect(patch: "/<%= ns_table_name %>/1").to route_to("<%= ns_table_name %>#update", id: "1") 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-4.0.0.beta4/lib/generators/rspec/scaffold/templates/show_spec.rb000066400000000000000000000014371360670111200270700ustar00rootroot00000000000000require '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-4.0.0.beta4/lib/generators/rspec/system/000077500000000000000000000000001360670111200223115ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/system/system_generator.rb000066400000000000000000000011151360670111200262260ustar00rootroot00000000000000require 'generators/rspec' if ::Rails::VERSION::STRING >= '5.1' module Rspec module Generators # @private class SystemGenerator < Base class_option :system_specs, type: :boolean, default: true, desc: "Generate system specs" def generate_system_spec return unless options[:system_specs] template template_name, File.join('spec/system', class_path, filename) end def template_name 'system_spec.rb' end def filename "#{table_name}_spec.rb" end end end end end rspec-rails-4.0.0.beta4/lib/generators/rspec/system/templates/000077500000000000000000000000001360670111200243075ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/system/templates/system_spec.rb000066400000000000000000000003161360670111200271720ustar00rootroot00000000000000require 'rails_helper' RSpec.describe "<%= class_name.pluralize %>", <%= type_metatag(:system) %> do before do driven_by(:rack_test) end pending "add some scenarios (or delete) #{__FILE__}" end rspec-rails-4.0.0.beta4/lib/generators/rspec/view/000077500000000000000000000000001360670111200217375ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/view/templates/000077500000000000000000000000001360670111200237355ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/generators/rspec/view/templates/view_spec.rb000066400000000000000000000002451360670111200262470ustar00rootroot00000000000000require 'rails_helper' RSpec.describe "<%= file_path %>/<%= @action %>", <%= type_metatag(:view) %> do pending "add some examples to (or delete) #{__FILE__}" end rspec-rails-4.0.0.beta4/lib/generators/rspec/view/view_generator.rb000066400000000000000000000011401360670111200253000ustar00rootroot00000000000000require '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-4.0.0.beta4/lib/rspec-rails.rb000066400000000000000000000053471360670111200202620ustar00rootroot00000000000000require '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' if ::Rails::VERSION::STRING >= '6.0' ::Rails::SourceAnnotationExtractor::Annotation.register_directories("spec") else SourceAnnotationExtractor::Annotation.register_directories("spec") end end generators = config.app_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 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) end end end end rspec-rails-4.0.0.beta4/lib/rspec/000077500000000000000000000000001360670111200166145ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/rspec/rails.rb000066400000000000000000000011021360670111200202450ustar00rootroot00000000000000require '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-4.0.0.beta4/lib/rspec/rails/000077500000000000000000000000001360670111200177265ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/rspec/rails/active_record.rb000066400000000000000000000017731360670111200230740ustar00rootroot00000000000000module 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-4.0.0.beta4/lib/rspec/rails/adapters.rb000066400000000000000000000114111360670111200220540ustar00rootroot00000000000000require '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 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 # @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 ::RSpec::Rails::Assertions. public_instance_methods. select do |m| m.to_s =~ /^(assert|flunk|refute)/ end 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 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-4.0.0.beta4/lib/rspec/rails/configuration.rb000066400000000000000000000137071360670111200231320ustar00rootroot00000000000000module 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 = { channel: %w[spec channels], 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], mailbox: %w[spec mailboxes] } # 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 Metrics/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 RSpec::Rails::FeatureCheck.has_action_mailer? config.include RSpec::Rails::MailerExampleGroup, type: :mailer end if RSpec::Rails::FeatureCheck.has_active_job? config.include RSpec::Rails::JobExampleGroup, type: :job end if RSpec::Rails::FeatureCheck.has_action_cable_testing? config.include RSpec::Rails::ChannelExampleGroup, type: :channel end if RSpec::Rails::FeatureCheck.has_action_mailbox? config.include RSpec::Rails::MailboxExampleGroup, type: :mailbox end end # rubocop:enable Metrics/MethodLength initialize_configuration RSpec.configuration end end rspec-rails-4.0.0.beta4/lib/rspec/rails/example.rb000066400000000000000000000012311360670111200217030ustar00rootroot00000000000000require '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' require 'rspec/rails/example/channel_example_group' require 'rspec/rails/example/mailbox_example_group' rspec-rails-4.0.0.beta4/lib/rspec/rails/example/000077500000000000000000000000001360670111200213615ustar00rootroot00000000000000rspec-rails-4.0.0.beta4/lib/rspec/rails/example/channel_example_group.rb000066400000000000000000000060331360670111200262470ustar00rootroot00000000000000require "rspec/rails/matchers/action_cable/have_streams" module RSpec module Rails # @api public # Container module for channel spec functionality. It is only available if # ActionCable has been loaded before it. module ChannelExampleGroup # @private module ClassMethods # These blank modules are only necessary for YARD processing. It doesn't # handle the conditional check below very well and reports undocumented objects. end end end end if RSpec::Rails::FeatureCheck.has_action_cable_testing? module RSpec module Rails # @api public # Container module for channel spec functionality. module ChannelExampleGroup extend ActiveSupport::Concern include RSpec::Rails::RailsExampleGroup include ActionCable::Connection::TestCase::Behavior include ActionCable::Channel::TestCase::Behavior # Class-level DSL for channel specs. module ClassMethods # @private def channel_class (_channel_class || described_class).tap do |klass| next if klass <= ::ActionCable::Channel::Base raise "Described class is not a channel class.\n" \ "Specify the channel class in the `describe` statement "\ "or set it manually using `tests MyChannelClass`" end end # @private def connection_class (_connection_class || described_class).tap do |klass| next if klass <= ::ActionCable::Connection::Base raise "Described class is not a connection class.\n" \ "Specify the connection class in the `describe` statement "\ "or set it manually using `tests MyConnectionClass`" end end end # Checks that the connection attempt has been rejected. # # @example # expect { connect }.to have_rejected_connection def have_rejected_connection raise_error(::ActionCable::Connection::Authorization::UnauthorizedError) end # Checks that the subscription is subscribed to at least one stream. # # @example # expect(subscription).to have_streams def have_streams check_subscribed! RSpec::Rails::Matchers::ActionCable::HaveStream.new end # Checks that the channel has been subscribed to the given stream # # @example # expect(subscription).to have_stream_from("chat_1") def have_stream_from(stream) check_subscribed! RSpec::Rails::Matchers::ActionCable::HaveStream.new(stream) end # Checks that the channel has been subscribed to a stream for the given model # # @example # expect(subscription).to have_stream_for(user) def have_stream_for(object) check_subscribed! RSpec::Rails::Matchers::ActionCable::HaveStream.new(broadcasting_for(object)) end end end end end rspec-rails-4.0.0.beta4/lib/rspec/rails/example/controller_example_group.rb000066400000000000000000000162751360670111200270330ustar00rootroot00000000000000module 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-4.0.0.beta4/lib/rspec/rails/example/feature_example_group.rb000066400000000000000000000047611360670111200263000ustar00rootroot00000000000000module 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) default_url_options[:host] ||= ::RSpec::Rails::FeatureExampleGroup::DEFAULT_HOST 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 (https://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-4.0.0.beta4/lib/rspec/rails/example/helper_example_group.rb000066400000000000000000000021101360670111200261060ustar00rootroot00000000000000require '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 def determine_constant_from_test_name(_ignore) described_class if yield(described_class) end end # Returns an instance of ActionView::Base with the helper being specified # mixed in, along with any of the built-in rails helpers. def helper _view.tap do |v| v.extend(ApplicationHelper) if defined?(ApplicationHelper) v.assign(view_assigns) end end private def _controller_path(example) example.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-4.0.0.beta4/lib/rspec/rails/example/job_example_group.rb000066400000000000000000000011321360670111200254040ustar00rootroot00000000000000module 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-4.0.0.beta4/lib/rspec/rails/example/mailbox_example_group.rb000066400000000000000000000041361360670111200262740ustar00rootroot00000000000000module RSpec module Rails # @api public # Container module for mailbox spec functionality. module MailboxExampleGroup extend ActiveSupport::Concern if RSpec::Rails::FeatureCheck.has_action_mailbox? require 'action_mailbox/test_helper' extend ::ActionMailbox::TestHelper # @private def self.create_inbound_email(arg) case arg when Hash create_inbound_email_from_mail(arg) else create_inbound_email_from_source(arg.to_s) end end else def self.create_inbound_email(_arg) raise "Could not load ActionMailer::TestHelper" end end class_methods do # @private def mailbox_class described_class end end included do subject { described_class } end # @api public # Passes if the inbound email was delivered # # @example # inbound_email = process(args) # expect(inbound_email).to have_been_delivered def have_been_delivered satisfy('have been delivered', &:delivered?) end # @api public # Passes if the inbound email bounced during processing # # @example # inbound_email = process(args) # expect(inbound_email).to have_bounced def have_bounced satisfy('have bounced', &:bounced?) end # @api public # Passes if the inbound email failed to process # # @example # inbound_email = process(args) # expect(inbound_email).to have_failed def have_failed satisfy('have failed', &:failed?) end # Process an inbound email message directly, bypassing routing. # # @param message [Hash, Mail::Message] a mail message or hash of # attributes used to build one # @return [ActionMaibox::InboundMessage] def process(message) MailboxExampleGroup.create_inbound_email(message).tap do |mail| self.class.mailbox_class.receive(mail) end end end end end rspec-rails-4.0.0.beta4/lib/rspec/rails/example/mailer_example_group.rb000066400000000000000000000021201360670111200261010ustar00rootroot00000000000000module 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 } 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-4.0.0.beta4/lib/rspec/rails/example/model_example_group.rb000066400000000000000000000004701360670111200257360ustar00rootroot00000000000000module 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-4.0.0.beta4/lib/rspec/rails/example/rails_example_group.rb000066400000000000000000000007711360670111200257540ustar00rootroot00000000000000# 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 include RSpec::Rails::MinitestAssertionAdapter include RSpec::Rails::FixtureSupport end end end rspec-rails-4.0.0.beta4/lib/rspec/rails/example/request_example_group.rb000066400000000000000000000014221360670111200263240ustar00rootroot00000000000000module 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-4.0.0.beta4/lib/rspec/rails/example/routing_example_group.rb000066400000000000000000000033171360670111200263300ustar00rootroot00000000000000require "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-4.0.0.beta4/lib/rspec/rails/example/system_example_group.rb000066400000000000000000000075141360670111200261700ustar00rootroot00000000000000module 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 # Special characters to translate into underscores for #method_name CHARS_TO_TRANSLATE = ['/', '.', ':', ',', "'", '"', " "].freeze # @private module BlowAwayTeardownHooks # @private def before_teardown end # @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 ].join("_").tr(CHARS_TO_TRANSLATE.join, "_")[0...200] + "_#{rand(1000)}" end # Delegates to `Rails.application`. def app ::Rails.application end included do |other| begin require 'capybara' require 'action_dispatch/system_test_case' rescue LoadError => e abort """ LoadError: #{e.message} 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 specs. """.gsub(/\s+/, ' ').strip end if ::Rails::VERSION::STRING >= '6.0' original_before_teardown = ::ActionDispatch::SystemTesting::TestHelpers::SetupAndTeardown.instance_method(:before_teardown) 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 BlowAwayTeardownHooks 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 self.class.before do # A user may have already set the driver, so only default if driver # is not set driven_by(:selenium) unless @driver end end def driven_by(*args, &blk) @driver = ::ActionDispatch::SystemTestCase.driven_by(*args, &blk).tap(&:use) end before do @routes = ::Rails.application.routes end after do orig_stdout = $stdout $stdout = StringIO.new begin if ::Rails::VERSION::STRING >= '6.0' original_before_teardown.bind(self).call end 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-4.0.0.beta4/lib/rspec/rails/example/view_example_group.rb000066400000000000000000000157171360670111200256220ustar00rootroot00000000000000require '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 StubResolverCache def self.resolver_for(hash) @resolvers ||= {} @resolvers[hash] ||= ActionView::FixtureResolver.new(hash) end end # @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 include ::Rails.application.routes.mounted_helpers 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(StubResolverCache.resolver_for(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 formats = if ActionView::Template::Types.respond_to?(:symbols) ActionView::Template::Types.symbols else [:html, :text, :js, :css, :xml, :json].map(&:to_s) end.map { |x| Regexp.escape(x) }.join("|") handlers = ActionView::Template::Handlers.extensions.map { |x| Regexp.escape(x) }.join("|") locales = "[a-z]{2}(?:-[A-Z]{2})?" variants = "[^.]*" path_regex = %r{ \A (?