## 1. Project Overview & Quickstart (rspec/DEVELOPMENT)

# Technical Documentation: rspec/DEVELOPMENT

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/rspec/DEVELOPMENT)

# DEVELOPMENT

### Agent Skills & Rules
- Discovered 21 agent rule(s) and prompt configurations.



--- METRICS ---
- Files Extracted: 1
- Estimated Token Budget: ~25 tokens
- Canonical Reference: https://codewiki.google/github.com/rspec/DEVELOPMENT


## 2. Official Technical Reference & Guides (rspec/rspec.github.io)

## File: README.md

rspec.github.io
===============

Source for https://rspec.info

Requires a recent version of Ruby (tested on 2.7.5, Ruby 3.x is not yet working), bundler and imagemagick (to generate favicons).

## Local Setup

* `brew install imagemagick` (or your package manager of choice).
* `brew install nodejs` (or your javascript runtime of choice for [execjs](https://github.com/rails/execjs)).
* `bundle install`
* `middleman build`

## Local Developing

Run `LIVERELOAD=true middleman server`

## Docker Setup + Development

If you don't have a local Ruby environment suitable to making changes to
rspec.info, or prefer containerised development; use the following scripts to
build the included Docker image and build the site in the containerised
environment instead.

```
# Start the middleman server. Access site at http://localhost:4567
bin/server

# Build the site in the `docs/` directory. Replacement for `middleman build`.
bin/build

# Start a console inside the docker container. Useful for debugging or running commands locally.
bin/console
```

## Deploying

We now use the Github action in `.github/workflows/middleman_deploy.yml` to automatically build
and deploy, builds are run on PR to ensure they "work" but you should check the artifacts locally
/ in the build before merging.

- To update [https://rspec-staging.github.io](https://rspec-staging.github.io) use repository https://github.com/RSpec-Staging/rspec-staging.github.io/.
- To update [https://rspec.info](https://rspec.info) use repository https://github.com/rspec/rspec.github.io/

## Credits

[Andrew Harvey](https://mootpointer.com) - for his incredible effort of making this repository as it is now

---

## File: license.md

The RSpec Website and its logo are licensed under a CC NC SA license, found below, the website design and logo were provided by a sponsorship package from Ninefold, a Macquarie Telecom company.

RSpec is copyright the RSpec development team.

# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License

By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.

## Section 1 – Definitions.

- **Adapted Material** means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.

- **Adapter's License** means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.

- **BY-NC-SA** Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.

- **Copyright and Similar Rights** means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.

- **Effective Technological Measures** means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.

- **Exceptions and Limitations** means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.

- **License Elements** means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.

- **Licensed Material** means the artistic or literary work, database, or other material to which the Licensor applied this Public License.

- **Licensed Rights** means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.

- **Licensor** means the individual(s) or entity(ies) granting rights under this Public License.

- **NonCommercial** means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.

- **Share** means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.

- **Sui Generis Database Rights** means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.

- **You** means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.

## Section 2 – Scope.

### License grant.

1. _Subject_ to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:

    a. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
  
    b. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.

2. _Exceptions and Limitations_. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.

3. _Term_. The term of this Public License is specified in Section 6(a).

4. _Media and formats_; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.

5. _Downstream recipients_.

    a. _Offer from the Licensor – Licensed Material_. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
  
    b. _Additional offer from the Licensor – Adapted Material_. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply.
  
    c. _No downstream restrictions_. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.

6. _No endorsement_. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).

### Other rights.

1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.

2. Patent and trademark rights are not licensed under this Public License.

3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.

## Section 3 – License Conditions.

Your exercise of the Licensed Rights is expressly made subject to the following conditions.

### Attribution.

1. If You Share the Licensed Material (including in modified form), You must:

    a. retain the following if it is supplied by the Licensor with the Licensed Material:

        1. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
    
        2. a copyright notice;
    
        3. a notice that refers to this Public License;
    
        4. a notice that refers to the disclaimer of warranties;
    
        5. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
    
    b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
    
    c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
  
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.

3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.

### ShareAlike.

In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.

1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.

2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.

3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.

## Section 4 – Sui Generis Database Rights.

Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:

a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;

b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and

c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.

For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.

## Section 5 – Disclaimer of Warranties and Limitation of Liability.

a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.

b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.

c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.

## Section 6 – Term and Termination.

a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.

b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:

    1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
    
    2. upon express reinstatement by the Licensor.

  For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
    
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
    
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.

## Section 7 – Other Terms and Conditions.

a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.

b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.

## Section 8 – Interpretation.

a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.

b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.

c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.

d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.

---

## File: source/_upgrade_summary.html.md

RSpec 3 includes many breaking changes, but our hope is to make this the smoothest
major-version gem upgrade you've ever done. To assist with that process, we've developed
RSpec 2.99 in tandem with RSpec 3. Every breaking change in 3.0 has a corresponding
deprecation to 2.99.  Rather than just giving you a generic upgrade document that describes
_all_ of the breaking changes (most of which affect very few users!), RSpec 2.99 gives you a
detailed upgrade checklist tailored to your project.

In addition, [Yuji Nakayama](https://twitter.com/nkym37) has created [Transpec](http://yujinakayama.me/transpec/) -- an absolutely amazing tool that can
automatically upgrade most RSpec suites. We've tried it on a few projects and have been _amazed_ at how well it works.

If you use `rspec-rails` you might want to read the
[upgrade notes](https://relishapp.com/rspec/rspec-rails/docs/upgrade)
specific to that gem.

---

## File: source/robots.txt

User-agent: GPTBot
Disallow: /

---

## File: source/blog/2011-11-04-recent-rspec-configuration-warnings-and-errors.html.md

---
title: Recent RSpec Configuration Warnings and Errors
author: Myron Marston
---

RSpec 2.6 introduced a deprecation warning when using `RSpec.configure {
... }` after defining an example group.  In RSpec 2.7, this warning was
removed, and now an error is raised when particular configuration
settings (`expect_with` and `mock_with`) are set after defining an
example group.

Recently, there have been comments and complaints on these changes
from [several](http://twitter.com/#!/elight/status/112166313518039040)
[different](http://twitter.com/#!/stevenharman/status/132251947473444864)
[people](http://twitter.com/#!/pda/status/129116122074185728)
on [twitter](http://twitter.com/#!/kytrinyx/status/116773198833532928).

I'm the one who made those changes to RSpec, and people are rightfully
annoyed with these changes...but there's a lot more to the story. I'm
not sure what the right solution is to the problem I was trying to solve
by making those changes, but I'm hoping that by blogging about it, we
can get some good ideas from the community.

## RSpec 2.0

One of the primary goals of RSpec 2 was to decouple the spec runner (rspec-core)
from the mocking framework (rspec-mocks) and the expectation framework
(rspec-expectations).  Besides the fact that decoupling is A Good Thing&trade;,
this separation opened up new possibilities for people to pick and
choose which parts of RSpec they want to use.

In particular, it allows people to use rspec-core to define and run their tests
using RSpec's example definition DSL (`describe`, `it`, `before`, `let`,
etc) while sticking with the `assert_foo` assertion methods from
Test::Unit or minitest, rather than using RSpec's `object.should whatever`
syntax. For better or worse, some people really dislike rspec-expectations
but love the runner.

RSpec 2 allows you to configure which you want to use:

~~~ ruby
# spec_helper.rb
RSpec.configure do |config|
  config.expect_with :stdlib
end

# or

RSpec.configure do |config|
  # not strictly necessary; this is the default config anyway
  config.expect_with :rspec
end
~~~

Both rspec-expectations and the standard library assertions are
available as modules--`RSpec::Matchers` and `Test::Unit::Assertions`,
respectively.  RSpec 2.0 to 2.5 included the appropriate module into
`RSpec::Core::ExampleGroup` just prior to running the examples (that is,
after all of them have been defined) to allow people to configure this
whenever they want.

Unfortunately, this triggered an unfortunate bug in ruby 1.9...which
I'll get to below.

## Infinite Recursion Issues

Shortly after RSpec 2 was released, we began to get some
[intermittent](http://groups.google.com/group/rspec/browse_thread/thread/eb54642fa0f051d1)
[reports](https://github.com/rspec/rspec-expectations/issues/63)
that users were occasionally getting a `SystemStackError` from
RSpec, indicating infinite recursion was occurring.  I myself saw this
error when working on the rspec-core specs at one point.

The recursion always happened in rspec-expectations' [method\_missing
hook](https://github.com/rspec/rspec-expectations/blob/v2.7.0/lib/rspec/matchers/method_missing.rb#L6-10).
In particular, the call to `super` triggered infinite recursion.

I found this very, very puzzling, and spent many hours troubleshooting
trying to figure out why `super` would infinitely recurse on itself.

## It's a Bug in Ruby 1.9

I eventually managed to boil the problem down to a simple rspec-less example:

~~~ ruby
# example.rb
module MyModule
  def some_method; super; end
end

class MyBaseClass; end

class MySubClass < MyBaseClass;
  include MyModule
end

# To trigger this bug, we must include the module in the base class after
# the module has already been included in the subclass.  If we move this line
# above the subclass declaration, this bug will not occur.
MyBaseClass.send(:include, MyModule)

MySubClass.new.some_method
~~~

If you run this on ruby 1.8, you will (correctly) get a `NoMethodError`.
On ruby 1.9, you get infinite recursion and a `SystemStackError`. Here's
my short explanation of the conditions that trigger this bug:

* Define a module that has a method that uses `super`.
* Include that module in a class _after_ it has already been included in one of its subclasses.
* Create an instance of said subclass and call the method.

Note that this error does not occur if the module is included in the
superclass _before_ it is included in the subclass.

## How this Bug Manifested Itself in RSpec

Here's how this bug manifested itself in RSpec:

* Every time you define an example group (using `describe` or `context`),
  RSpec creates a new subclass of `RSpec::Core::ExampleGroup`, or a
  subclass-of-a-subclass, if you have nested your example group within
  another one.
* Some users included `RSpec::Matchers` into their example groups.
  [Here's one example](https://github.com/radar/forem/blob/a9ce93d15fa77dbb3c586c3583dda49e70750809/spec/support/integration_example_group.rb#L13).
* As I explained above, in 2.0 to 2.5, RSpec included `RSpec::Matchers` in
  `RSpec::Core::ExampleGroup` right before running the examples, _after_
  all examples have been defined (and hence, after the user may have
  already included `RSpec::Matchers` in their example groups).
* When a user called an undefined or misspelled method from an example,
  it would trigger this error.

## Fixing the Issue...by Introducing Other Problems :(

To prevent users from getting infinite recursion, we need to prevent
`RSpec::Matchers` (and really, any other module that may use `super`)
from being included in an example group before it is included in
`RSpec::Core::ExampleGroup`. At one point, I considered adding a hook to
either `RSpec::Core::ExampleGroup` or `RSpec::Matchers` to detect when a
user is including it, and somehow prevent or warn them.  However, I
quickly realized that the extreme flexibility of Ruby's module system
makes this very complicated. A user may not be including
`RSpec::Matchers` directly; they may be including a module from some
library or plugin, that itself includes `RSpec::Matchers`, or includes a
module that includes `RSpec::Matchers`. I realized this wasn't going to
be a simple solution to get right.

Instead, after talking with [David
Chelimsky](http://twitter.com/#!/dchelimsky) and some other members of the
RSpec core team, we decided it was best to change when `RSpec::Matchers`
gets included. By including `RSpec::Matchers` in
`RSpec::Core::ExampleGroup` before it has been subclassed the issue goes away entirely.

We still wanted to let people configure `expect_with :stdlib`, though.
the best solution we could come up with is to delay the inclusion of the
expectation module until the moment when `RSpec::Core::ExampleGroup` is
being subclassed for the first time. This gives the user a chance to
configure `expect_with :stdlib` as long as they do so before defining
any example groups. Once an example group has been defined, we
automatically default to `expect_with :rspec`--which means that any
future `expect_with` configuration would be effectively ignored.

[Here's the commit](https://github.com/rspec/rspec-core/commit/622a4b7ac41e0ab6a4786070cca3ff866b72b57c),
if you're interested.  You'll notice that it also changes when the
mocking framework adapter module gets included.  Since we don't want to deal
with this issue again if/when one of the mocking framework adapter
modules uses `super`, I thought it best to change it as well.

This whole issue suggested to me that it's problematic to allow users to
configure RSpec after defining examples.  In my mind, since the
configuration affects how RSpec works, it's best to set it _before_ you
start to use RSpec (i.e. by defining examples).  I [made a
change](https://github.com/rspec/rspec-core/commit/fc70cee014689a947bfdea1ab04d91191327946f)
to cause RSpec to print a deprecation warning when you use
`RSpec.configure` after defining an example group.

In retrospect, I should have realized that this would affect a lot of
users. At the time, it didn't occur to me that it would. I do all of my
RSpec configuration before defining any example groups and I assumed
that's what everyone else did, too. The deprecation warning was mostly
just put there on the off chance that someone might configure RSpec
after defining an example.

## RSpec 2.6

RSpec 2.6 was released with these changes and we immediately began
getting questions and complaints
about this warning. People like [Gary Bernhardt](http://twitter.com/#!/garybernhardt)
and [Corey Haines](http://twitter.com/#!/coreyhaines) have a technique
of speeding up their tests by loading as little as possible--and this
usually involves not loading `spec_helper` from each spec file. This can
trigger the deprecation warning when one spec file (say,
`spec/lib/my_class_spec.rb`) does not require `spec_helper`, but another file in
the same suite (say `spec/models/user_spec.rb`) does.  If
`spec/lib/my_class_spec.rb` is
loaded before `spec/models/user_spec.rb` (which usually happens--they tend to
get loaded in alphabetical order), it will trigger the warning since
examples are defined in `spec/lib/my_class_spec.rb` before the configuration
happens in `spec_helper.rb`.

I'm a big fan of the "don't load spec\_helper" approach now, but at the time I made the changes,
I had never heard or thought of doing it that way.

We had a conversation about this on an [rspec-rails issue](https://github.com/rspec/rspec-rails/issues/371).
The best suggestion to come out of that (and one that no one argued
against) was to remove the warning, and instead raise an error on the
specific, problematic configs (`expect_with` and `mock_with`), if they
get set after defining an example group.

I made [this change](https://github.com/rspec/rspec-core/commit/f46e00aff4c9aa028991ff57e71d54f3dcd5c307)
and it was released in RSpec 2.7.

## RSpec 2.7

After RSpec 2.7 came out, there were yet more complaints about this
change. Now some users were unable to run their specs because of the
error. Effectively, this had made the problem worse--the previous
warning could be ignored, but not the error.

I [committed a change](https://github.com/rspec/rspec-core/commit/f2dc2f8954fc6663dc45f03375912dc58fc590f9)
a few days ago that should improve things here: instead of raising an error anytime
`expect_with` or `mock_with` are called after an example group is
defined, the error is only raised if the method call is changing the
setting. No error will be raised if you're simply explicitly setting the
default (i.e. `mock_with :rspec`) or re-setting the existing config
value.

This is certainly an important, needed change that I simply didn't
consider when I made the previous changes.  I apologize.

Note that this does not remove the error entirely: if you are
configuring RSpec to use a different expectation/assertion framework or
mocking framework, this must still be done _before_ an example group is
defined so that RSpec can include the appropriate module in
`RSpec::Core::ExampleGroup` _before_ it has been subclassed.

## Avoiding these warnings/errors

If you're on RSpec 2.6 or 2.7 and have gotten these warnings or errors,
there are some very simple changes you can make to avoid them.

First, make sure all of your spec\_helper requires are simply `require
'spec_helper'`. If you use a path relative to `__FILE__`, as people
often do, spec\_helper.rb can be loaded multiple times (since ruby will
happily re-require a file if it is specified as a different file path).
RSpec puts the spec directoy on the load path for you, so you can (and
generally should) just require `spec_helper`.

Second, if you follow the "don't load spec\_helper" approach, and
you need to configure either `expect_with` or `mock_with`, you'll
need to create a secondary helper file for your isolated, fast specs.

Here's one way to do it:

~~~ ruby
# spec/fast_spec_helper.rb
require 'rspec'

RSpec.configure do |c|
  c.mock_with :mocha
end
~~~

~~~ ruby
# spec/spec_helper.rb
require 'fast_spec_helper'

# load rails or whatever to get your full app environment booted

RSpec.configure do |c|
  # other RSpec configuration
end
~~~

~~~ ruby
# spec/lib/my_class_spec.rb
require 'fast_spec_helper'

describe MyClass do
end
~~~

~~~ ruby
# spec/controllers/my_controller_spec.rb
require 'spec_helper'

describe MyController do
end
~~~

I know this goes against the "don't load spec\_helper" approach a bit,
but the important thing is that the rails/sinatra/whatever environment
is not fully loaded in the isolated specs.  We're using
fast\_spec\_helper.rb to only configure the bare minimum--the specific
`expect_with` or `mock_with` settings that must be set before an
example group is defined. The one extra require isn't going to make a
noticeable difference in the speed of your isolated tests.

Of course, if you are just setting `mock_with` or `expect_with` to the
default (`:rspec`) then you should just remove that configuration
entirely and the error should go away--no need for a separate
`fast_spec_helper.rb` file.

Alternatively, you could use ruby's `-r` flag to force a helper file to
be loaded before any isolated specs, rather than having to require
a helper file from each.

## Is There a Better Way to Work Around this Bug?

So there you have it...the full story behind the recent configuration
warnings and errors in RSpec. I apologize if this has caused upgrade
pain for you. I solved the issues in the best way I could figure out.

If you think I totally screwed up, or if you can think of a better way
to deal with the ruby 1.9 bug, please let me know in the comments!

Also, I [filed a bug](http://redmine.ruby-lang.org/issues/5236) on
the ruby issue tracker. Please comment there if you would like to see it
fixed.

---

## File: source/blog/2012-06-15-rspecs-new-expectation-syntax.html.md

---
title: RSpec's New Expectation Syntax
author: Myron Marston
---

RSpec has featured a readable english-like syntax for setting
expectations for a long time:

~~~ ruby
foo.should eq(bar)
foo.should_not eq(bar)
~~~

RSpec 2.11 will include a new variant to this syntax:

~~~ ruby
expect(foo).to eq(bar)
expect(foo).not_to eq(bar)
~~~

There are a few things motivating this new syntax, and I wanted
to blog about it to spread awareness.

## Delegation Issues

Between `method_missing`, `BasicObject` and the standard library's
`delegate`, ruby has very rich tools for building delegate or proxy
objects. Unfortunately, RSpec's `should` syntax, as elegantly as it
reads, is prone to producing weird, confusing failures when testing
delegate/proxy objects.

Consider a simple proxy object that subclasses `BasicObject`:

~~~ ruby
# fuzzy_proxy.rb
class FuzzyProxy < BasicObject
  def initialize(target)
    @target = target
  end

  def fuzzy?
    true
  end

  def method_missing(*args, &block)
    @target.__send__(*args, &block)
  end
end
~~~

Simple enough; it defines a `#fuzzy?` predicate, and delegates all
other method calls to the target object.

Here's a simple spec to test its fuzziness:

~~~ ruby
# fuzzy_proxy_spec.rb
describe FuzzyProxy do
  it 'is fuzzy' do
    instance = FuzzyProxy.new(:some_object)
    instance.should be_fuzzy
  end
end
~~~

Surprisingly, this fails:

~~~
  1) FuzzyProxy is a fuzzy proxy
     Failure/Error: instance.should be_fuzzy
     NoMethodError:
       undefined method `fuzzy?' for :some_object:Symbol
     # ./fuzzy_proxy.rb:11:in `method_missing'
     # ./fuzzy_proxy_spec.rb:6:in `block (2 levels) in <top (required)>'

Finished in 0.01152 seconds
1 example, 1 failure
~~~

The problem is that rspec-expectations defines `should` on `Kernel`,
and `BasicObject` does not include `Kernel`...so `instance.should`
triggers `method_missing` and gets delegated to the target object.
The result is actually `:some_object.should be_fuzzy` which is
clearly false (or rather, a `NoMethodError`).

It gets even more confusing when using `delegate` in the standard
library. It [selectively
includes](https://github.com/ruby/ruby/blob/v1_9_3_194/lib/delegate.rb#L43-50)
some of `Kernel`'s methods...which means that if rspec-expectations gets
loaded before `delegate`, `should` will work properly on delegate
objects, but if `delegate` is loaded first, it will proxy the `should`
calls just like in our `FuzzyProxy` example above.

The underlying problem is RSpec's `should` syntax: for `should` to
work properly, it must be defined on every object in the system...
but RSpec does not own every object in the system and cannot ensure
that it always works consistently. As we've seen, it doesn't work
as RSpec expects on proxy objects. Note that this isn't just a
problem with RSpec; it's a problem with minitest/spec's `must_xxx`
syntax as well.

The solution we came up with is the new `expect` syntax:

~~~ ruby
# fuzzy_proxy_spec.rb
describe FuzzyProxy do
  it 'is fuzzy' do
    instance = FuzzyProxy.new(:some_object)
    expect(instance).to be_fuzzy
  end
end
~~~

This does not rely on any methods being present on all objects
in the system, and thus avoids the underlying problem altogether.

## (Almost) All Matchers Are Supported

The new `expect` syntax looks different from the old
`should` syntax, but under the covers, it's essentially
the same. You pass a matcher to the `#to` method, and
it fails the example if it does not match.

All matchers are supported, with an important exception:
the `expect` syntax does not directly support the operator
matchers.

~~~ ruby
# rather than:
foo.should == bar

# ...use:
expect(foo).to eq(bar)
~~~

While operator matchers are intuitive to use, they require
special handling in RSpec for them to work right, due to Ruby's
precedence rules. Furthermore, `should ==` generates a ruby
warning[^foot_1], and people have been occasionally surprised by
the fact that `should !=` does not work as they might expect[^foot_2].

The new syntax affords us the chance to make a clean
break from the inconsistencies of the operator matchers
without the risk of breaking existing test suites, so
we decided not to support operator matchers with
the new syntax. Here's a listing of each of the old
operator matchers (used with `should`), and their `expect` equivalent:

~~~ ruby
foo.should == bar
expect(foo).to eq(bar)

"a string".should_not =~ /a regex/
expect("a string").not_to match(/a regex/)

[1, 2, 3].should =~ [2, 1, 3]
expect([1, 2, 3]).to match_array([2, 1, 3])
~~~

You may have noticed I didn't list the comparison matchers
(e.g. `x.should < 10`)--that's because they work but have
never been recommended. Who says "x should less than 10"?
They were always intended to be used with `be`, which
both reads better and continues to work:

~~~ ruby
foo.should be < 10
foo.should be <= 10
foo.should be > 10
foo.should be >= 10
expect(foo).to be < 10
expect(foo).to be <= 10
expect(foo).to be > 10
expect(foo).to be >= 10
~~~

## Unification of Block vs. Value Syntaxes

`expect` has actually been available in RSpec for a long
time[^foot_3] in a limited form, as a more-readable alternative
for block expectations:

~~~ ruby
# rather than:
lambda { do_something }.should raise_error(SomeError)

# ...you can do:
expect { something }.to raise_error(SomeError)
~~~

Before RSpec 2.11, `expect` would not accept any normal arguments,
and could not be used for value expectations. With the changes
in 2.11, it's nice to have the unity of the same syntax for both
kinds of expectations.

## Configuration Options

By default, both the `should` and `expect` syntaxes are
available. However, if you want to use only one syntax
or the other, you can configure RSpec:

~~~ ruby
# spec_helper.rb
RSpec.configure do |config|
  config.expect_with :rspec do |c|
    # Disable the `expect` sytax...
    c.syntax = :should

    # ...or disable the `should` syntax...
    c.syntax = :expect

    # ...or explicitly enable both
    c.syntax = [:should, :expect]
  end
end
~~~

For example, if you're starting a new project, and you want
to ensure only `expect` is used for consistency, you can disable
`should` entirely. When one of the syntaxes is disabled, the
corresponding method will simply be undefined.

In the future, we plan to change the defaults so that only
`expect` is available unless you explicitly enable `should`.
We may do this as soon as RSpec 3.0, but we want to give
users plenty of time to get acquianted with it.

Let us know what you think!

[^foot_1]: As [Mislav reports](https://mislav.net/2011/06/ruby-verbose-mode/), when warnings are turned on, you can get a "Useless use of == in void context" warning.

[^foot_2]: On ruby 1.8, `x.should != y` is syntactic sugar for `!(x.should == y)` and RSpec has no way to distinguish `should ==` from `should !=`. On 1.9, we can distinguish between them (since `!=` can now be defined as a separate method), but it would be confusing to support it on 1.9 but not on 1.8, so we [decided to just raise an error instead](https://github.com/rspec/rspec-expectations/issues/33).

[^foot_3]: It was originally added [over 3 years ago!](https://github.com/dchelimsky/rspec/commit/7e4f872b4becbd41588da95c0e5d954a6e770293)

---

## File: source/blog/2012-06-29-constant-stubbing-in-rspec-2-11.html.md

---
title: Constant Stubbing in RSpec 2.11
author: Myron Marston
---

In the 2.11 release, rspec-mocks is gaining a significant new
capability that, as far as I know, isn't provided by any other
ruby mocking library: constant stubbing[^foot_1].

Let's look at the API, and then talk a bit about some of
the use cases for it.

## The API

The main API is `stub_const`:

~~~ ruby
describe "stub_const" do
  it "changes the constant value for the duration of the example" do
    stub_const("Foo::SIZE", 10)
    expect(Foo::SIZE).to eq(10)
  end
end
~~~

This works for both defined and undefined constants; you
could stub `A::B::C::D::E::F` even if none of the intermediary
constants exist. When the example completes, the constants will
be restored to their original states: any newly defined constants
will be undefined, and any modified constants will be restored
to their original values.

Note that constant names must be fully qualified; the current
module nesting is not considered:

~~~ ruby
module MyGem
  class SomeClass; end
end

module MyGem
  describe "Something" do
    let(:fake_class) { Class.new }

    it "accidentally stubs the wrong constant" do
      # this stubs ::SomeClass (in the top-level namespace),
      # not MyGem::SomeClass like you probably mean.
      stub_const("SomeClass", fake_class)
    end

    it "stubs the right constant" do
      stub_const("MyGem::SomeClass", fake_class)
    end
  end
end
~~~

`stub_const` also supports a `:transfer_nested_constants` option.
Consider a case where you have nested constants:

~~~ ruby
class CardDeck
  SUITS = [:spades, :diamonds, :clubs, :hearts]
  NUM_CARDS = 52
end
~~~

`stub_const("CardDeck", fake_class)` cuts off access to the
nested constants (`CardDeck::SUITS` and `CardDeck::NUM_CARDS`),
unless you manually assign `fake_class::SUITS` and
`fake_class::NUM_CARDS`. The `:transfer_nested_constants`
option is provided to take care of this for you:

~~~ ruby
# Default behavior:
fake_class = Class.new
stub_const("CardDeck", fake_class)
CardDeck # => fake_class
CardDeck::SUITS # => raises uninitialized constant error
CardDeck::NUM_CARDS # => raises uninitialized constant error

# `:transfer_nested_constants => true` transfers all nested constants:
stub_const("CardDeck", fake_class, :transfer_nested_constants => true)
CardDeck::SUITS # => [:spades, :diamonds, :clubs, :hearts]
CardDeck::NUM_CARDS # => 52

# Or you can specify a list of constants to transfer:
stub_const("CardDeck", fake_class, :transfer_nested_constants => [:SUITS])
CardDeck::SUITS # => [:spades, :diamonds, :clubs, :hearts]
CardDeck::NUM_CARDS # => raises uninitialized constant error
~~~

## Use Cases

I've found this useful in a few different situations:

* It provides a simple way to change a class setting expressed as
  a constant for one test. In the past, I've often defined static
  class methods just so they could be stubbed, even though it
  made more sense to use a constant. Now you can just use a constant!
* It makes dependency injection easy when the class-under-test
  depends on a collaborator's class method (e.g. when the collaborator
  is stateless). You can easily stub the collaborator's class constant
  with a test double.
* It makes stubbing unloaded dependencies dead-simple. Gary
  Bernhardt discussed this situation at length in [Destroy all
  Software #46](https://www.destroyallsoftware.com/screencasts/catalog/stubbing-unloaded-dependencies).
  He mentioned mutating constants as a possible way of stubbing unloaded
  dependencies, but recommended against it because of the complexity
  of safely managing this. Now that rspec-mocks can do it for you, it's
  far less complex, and much, much safer.

If you're curious how it all works, check out the [source on
github](https://github.com/rspec/rspec-mocks/blob/2-11-maintenance/lib/rspec/mocks/stub_const.rb).

[^foot_1]: Actually, this has been available in [rspec-fire](https://github.com/xaviershay/rspec-fire) for a good four months or so. But it's not really a full mocking library...it builds on top of rspec-mocks, and now this functionality has been ported over to rspec-mocks.

---

## File: source/blog/2012-07-23-mixing-and-matching-parts-of-rspec.html.md

---
title: Mixing and Matching Parts of RSpec
author: Myron Marston
---

RSpec was split into three subprojects for the last major release
(2.0):

* rspec-core: The test runner and main DSL (`describe`, `it`, `before`,
  `after`, `let`, `shared_examples`, etc).
* rspec-expectations: Provides a readable syntax for specifying the
  expected outcomes of your tests using matchers.
* rspec-mocks: RSpec's test-double framework.

One of the cool things about this is that it allows you to mix and
match parts of RSpec with other testing libraries. Unfortunately, even
though RSpec 2 has been out for over 18 months, there's not a lot of
good information out there about how to do that.

I want to correct that by showing a few examples of the possibilities.

All of the examples below have some setup/configuration code at the top
that you would probably want to extract into `test_helper.rb` or
`spec_helper.rb` in a real project.

I made a [github
project](https://github.com/myronmarston/mix_and_match_rspec) with
all these examples, so check that out if you want some code you can
play with.

## Using rspec-core with another assertion library

If you like RSpec's test runner, but don't like the syntax and
failure output provided by rspec-expectations, you can use the
assertions from the standard library provided by
[MiniTest](http://ruby-doc.org/stdlib-1.9.3/libdoc/minitest/unit/rdoc/MiniTest/Assertions.html):

~~~ ruby
# rspec_and_minitest_assertions.rb
require 'set'

RSpec.configure do |rspec|
  rspec.expect_with :stdlib
end

describe Set do
  specify "a passing example" do
    set = Set.new
    set << 3 << 4
    assert_include set, 3
  end

  specify "a failing example" do
    set = Set.new
    set << 3 << 4
    assert_include set, 5
  end
end
~~~

The output:

~~~
$ rspec rspec_and_minitest_assertions.rb 
.F

Failures:

  1) Set a failing example
     Failure/Error: assert_include set, 5
     MiniTest::Assertion:
       Expected #<Set: {3, 4}> to include 5.
     # ./rspec_and_minitest_assertions.rb:17:in `block (2 levels) in <top (required)>'

Finished in 0.00093 seconds
2 examples, 1 failure

Failed examples:

rspec ./rspec_and_minitest_assertions.rb:14 # Set a failing example
~~~

[Wrong](https://github.com/sconover/wrong/) is an interesting
alternative that uses a single method (`assert` with a block) to
provide detailed failure output:

~~~ ruby
# rspec_and_wrong.rb
require 'set'
require 'wrong'

RSpec.configure do |rspec|
  rspec.expect_with Wrong
end

describe Set do
  specify "a passing example" do
    set = Set.new
    set << 3 << 4
    assert { set.include?(3) }
  end

  specify "a failing example" do
    set = Set.new
    set << 3 << 4
    assert { set.include?(5) }
  end
end
~~~

The output:

~~~
$ rspec rspec_and_wrong.rb
.F

Failures:

  1) Set a failing example
     Failure/Error: assert { set.include?(5) }
     Wrong::Assert::AssertionFailedError:
       Expected set.include?(5), but
           set is #<Set: {3, 4}>
     # ./rspec_and_wrong.rb:18:in `block (2 levels) in <top (required)>'

Finished in 0.04012 seconds
2 examples, 1 failure

Failed examples:

rspec ./rspec_and_wrong.rb:15 # Set a failing example
~~~

As demonstrated by these examples, you simply configure `expect_with` to
use an alternate library. You can specify `:stdlib`, `:rspec` (to be
explicit about using rspec-expectations) or any module; the module will
be mixed in to the example context.

## Using minitest and rspec-expectations

If you like running your tests with MiniTest but prefer
the syntax and failure output of rspec-expectations, you
can combine them:

~~~ ruby
# minitest_and_rspec_expectations.rb
require 'minitest/autorun'
require 'rspec/expectations'
require 'set'

RSpec::Matchers.configuration.syntax = :expect

module MiniTest
  remove_const :Assertion # so we can re-assign it w/o a ruby warning

  # So expectation failures are considered failures, not errors.
  Assertion = RSpec::Expectations::ExpectationNotMetError

  class Unit::TestCase
    include RSpec::Matchers

    # So each use of `expect` is counted as an assertion...
    def expect(*a, &b)
      assert(true)
      super
    end
  end
end

class TestSet < MiniTest::Unit::TestCase
  def test_passing_expectation
    set = Set.new
    set << 3 << 4
    expect(set).to include(3)
  end

  def test_failing_expectation
    set = Set.new
    set << 3 << 4
    expect(set).to include(5)
  end
end
~~~

The output:

~~~
$ ruby minitest_and_rspec_expectations.rb
Run options: --seed 12759

# Running tests:

.F

Finished tests in 0.001991s, 1004.5203 tests/s, 1004.5203 assertions/s.

  1) Failure:
test_failing_expectation(TestSet)
[/Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-expectations-2.11.1/lib/rspec/expectations/handler.rb:17]:
expected #<Set: {3, 4}> to include 5

2 tests, 2 assertions, 1 failures, 0 errors, 0 skips
~~~

Let's take the integration code bit-by-bit:

* `RSpec::Matchers.configuration.syntax = :expect` configures the
  desired rspec-expectations syntax to just the [new expect
  syntax](/blog/2012/06/rspecs-new-expectation-syntax). By
  default, both the old `should` and the new `expect` syntaxes
  are available.
* MiniTest treats `MiniTest::Assertion` exceptions differently
  from other errors, counting them as test failures rather
  than errors in the output. We re-assign the constant to
  `RSpec::Expectations::ExpectationNotMetError` in order to
  have our expectation failures counted as failures, not errors.
* MiniTest's output includes a count of the total number of assertions and
  the number of assertions per second. We add a call to `assert(true)`
  every time `expect` is called so the counts are correct.
* Finally, we include `RSpec::Matchers` into the test context
  to make `expect` and the matchers available.

For other test runners, you could probably get by with just
mixing `RSpec::Matchers` into your test context--most of the
rest of this is MiniTest-specific.

## Using minitest and rspec-mocks

MiniTest features a mock object framework, that, in [the words of the
README](https://github.com/seattlerb/minitest/blob/master/lib/minitest/mock.rb),
"is a beautifully tiny mock (and stub) object framework". It is indeed
beautiful and tiny. However, rspec-mocks has many more features, and
if you like those features, you can easily use it with MiniTest:

~~~ ruby
# minitest_and_rspec_mocks.rb
require 'minitest/autorun'
require 'rspec/mocks'

MiniTest::Unit::TestCase.add_setup_hook do |test_case|
  RSpec::Mocks.setup(test_case)
end

MiniTest::Unit::TestCase.add_teardown_hook do |test_case|
  begin
    RSpec::Mocks.verify
  ensure
    RSpec::Mocks.teardown
  end
end

class TestSet < MiniTest::Unit::TestCase
  def test_passing_mock
    foo = mock
    foo.should_receive(:bar)
    foo.bar
  end

  def test_failing_mock
    foo = mock
    foo.should_receive(:bar)
  end

  def test_stub_real_object
    Object.stub(foo: "bar")
    assert_equal "bar", Object.foo
  end
end
~~~

The output:

~~~
$ ruby minitest_and_rspec_mocks.rb 
Run options: --seed 27480

# Running tests:

..E

Finished tests in 0.002546s, 1178.3189 tests/s, 392.7730 assertions/s.

  1) Error:
test_failing_mock(TestSet):
RSpec::Mocks::MockExpectationError: (Mock).bar(any args)
    expected: 1 time
    received: 0 times
    minitest_and_rspec_mocks.rb:25:in `test_failing_mock'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks/error_generator.rb:87:in `__raise'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks/error_generator.rb:46:in `raise_expectation_error'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks/message_expectation.rb:259:in `generate_error'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks/message_expectation.rb:215:in `verify_messages_received'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks/method_double.rb:117:in `block in verify'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks/method_double.rb:117:in `each'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks/method_double.rb:117:in `verify'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks/proxy.rb:96:in `block in verify'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks/proxy.rb:96:in `each'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks/proxy.rb:96:in `verify'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks/methods.rb:116:in `rspec_verify'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks/space.rb:11:in `block in verify_all'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks/space.rb:10:in `each'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks/space.rb:10:in `verify_all'
    /Users/myron/.rvm/gems/ruby-1.9.3-p194/gems/rspec-mocks-2.11.1/lib/rspec/mocks.rb:19:in `verify'
    minitest_and_rspec_mocks.rb:10:in `block in <main>'

3 tests, 1 assertions, 0 failures, 1 errors, 0 skips
~~~

The integration here is a little more manual, but it's not bad:

* Call `RSpec::Mocks.setup(test)` before each test or example to ensure
  things are setup properly.
* Call `RSpec::Mocks.verify` after each test or example so that mock
  expectations are checked.
* Call `RSpec::Mocks.teardown` at the very end to ensure that any
  modifications to real objects (for a stub, for example) are cleaned
  up. Note: this _must_ be called after every test (even failing ones)
  to prevent stubs from "leaking" outside of a given test. That's why
  I put this in the `ensure` clause above.

## Using rspec-core with another mocking library

RSpec can easily be used with an alternate mocking library.
In fact, many RSpec users prefer
[Mocha](http://gofreerange.com/mocha/docs/) to rspec-mocks,
and the two can integrate just fine:

~~~ ruby
# rspec_and_mocha.rb
RSpec.configure do |rspec|
  rspec.mock_with :mocha
end

describe "RSpec and Mocha" do
  specify "a passing mock" do
    foo = mock
    foo.expects(:bar)
    foo.bar
  end

  specify "a failing mock" do
    foo = mock
    foo.expects(:bar)
  end

  specify "stubbing a real object" do
    foo = Object.new
    foo.stubs(bar: 3)
    expect(foo.bar).to eq(3)
  end
end
~~~

The output:

~~~
rspec rspec_and_mocha.rb 
.F.

Failures:

  1) RSpec and Mocha a failing mock
     Failure/Error: foo.expects(:bar)
     Mocha::ExpectationError:
       not all expectations were satisfied
       unsatisfied expectations:
       - expected exactly once, not yet invoked: #<Mock:0x7fcc01844840>.bar(any_parameters)
     # ./rspec_and_mocha.rb:14:in `block (2 levels) in <top (required)>'

Finished in 0.00388 seconds
3 examples, 1 failure

Failed examples:

rspec ./rspec_and_mocha.rb:12 # RSpec and Mocha a failing mock
~~~

You can similarly configure `mock_with :flexmock` or
`mock_with :rr` to use one of those mocking libraries.  I didn't
include those examples here because they're configured in the
exact same way, but [the github
repo](https://github.com/myronmarston/mix_and_match_rspec) containing
all the examples in this blog post has examples for them, too.

## Conclusion

It takes some extra leg work, but most of ruby's testing tools
can integrate with each other without any problems, so don't
feel constrained to use all of MiniTest or all of RSpec if
there's parts you love and parts you dislike. Use a testing
stack that best meets your needs.

---

## File: source/blog/2013-02-23-rspec-2-13-is-released.html.md

---
title: RSpec 2.13 is released!
author: Myron Marston
---

I've just released RSpec 2.13. It's a minor release containing a few
backward-compatible enhancements and lots of bug fixes. It is a
recommended upgrade for all users.

Thanks to all the contributors who helped make this RSpec release happen.

## Notable New Features

### Profile more than 10 examples

RSpec has featured a `--profile` option for a long time. It dumps a
report of the 10 slowest examples. Now you can pass a numeric option
to have it print more than 10 examples.

To print off the 15 slowest examples, you could use:

~~~
rspec --profile 15
~~~

### `let` and `subject` declarations can use `super`

Users have requested this for a while. This allows to override a `let` or `subject`
declaration in a nested group while delegating to the original definition from the
parent group. Just use `super()`:

~~~ ruby
describe Array do
  let(:numbers) { [1, 2, 3, 4] }

  context "when evens are filtered out" do
    let(:numbers) { super().reject(&:even?) }
  end
end
~~~

Note that to use this feature, you _must_ use explicit parens
in the call to `super`; otherwise ruby will give you an ugly
`implicit argument passing of super from method defined by
define_method() is not supported` error.

### `be_within` matcher supports percent deltas

This is best illustrated by an example:

~~~ ruby
# The existing `be_within` matcher (which still works):
expect(account.balance).to be_within(10).of(500)

# Now you can do this, too:
expect(account.balance).to be_within(2).percent_of(500)
~~~

### `include` matcher can accept a list of matchers

This is handy when you want to verify something about the
items in a list rather that simply verifying the items' identity.

~~~ ruby
RSpec::Matchers.define :a_user_named do |name|
  match do |user|
    user.name == name
  end
end

expect(users).to include(a_user_named("Coen"), a_user_named("Daphne"))
~~~

## Docs

### RDoc

* [http://rubydoc.info/gems/rspec-core](http://rubydoc.info/gems/rspec-core)
* [http://rubydoc.info/gems/rspec-expectations](http://rubydoc.info/gems/rspec-expectations)
* [http://rubydoc.info/gems/rspec-mocks](http://rubydoc.info/gems/rspec-mocks)
* [http://rubydoc.info/gems/rspec-rails](http://rubydoc.info/gems/rspec-rails)

### Cucumber Features

* [http://relishapp.com/rspec/rspec-core](http://relishapp.com/rspec/rspec-core)
* [http://relishapp.com/rspec/rspec-expectations](http://relishapp.com/rspec/rspec-expectations)
* [http://relishapp.com/rspec/rspec-mocks](http://relishapp.com/rspec/rspec-mocks)
* [http://relishapp.com/rspec/rspec-rails](http://relishapp.com/rspec/rspec-rails)

## Release Notes

### rspec-core 2.13.0

[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.12.2...v2.13.0)

Enhancements

* Allow `--profile` option to take a count argument that
  determines the number of slow examples to dump
  (Greggory Rothmeier).
* Add `subject!` that is the analog to `let!`. It defines an
  explicit subject and sets a `before` hook that will invoke
  the subject (Zubin Henner).
* Fix `let` and `subject` declaration so that `super`
  and `return` can be used in them, just like in a normal
  method. (Myron Marston)
* Allow output colors to be configured individually.
  (Charlie Maffitt)

Bug fixes

* Don't blow up when dumping error output for instances
  of anonymous error classes (Myron Marston).
* Fix default backtrace filters so lines from projects
  containing "gems" in the name are not filtered, but
  lines from installed gems still are (Myron Marston).
* Fix autotest command so that is uses double quotes
  rather than single quotes for windows compatibility
  (Jonas Tingeborn).
* Fix `its` so that uses of `subject` in a `before` or `let`
  declaration in the parent group continue to reference the
  parent group's subject. (Olek Janiszewski)

### rspec-expectations 2.13.0

[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.12.1...v2.13.0)

Enhancements

* Add support for percent deltas to `be_within` matcher:
  `expect(value).to be_within(10).percent_of(expected)`
  (Myron Marston).
* Add support to `include` matcher to allow it to be given a list
  of matchers as the expecteds to match against (Luke Redpath).

Bug fixes

* Fix `change` matcher so that it dups strings in order to handle
  mutated strings (Myron Marston).
* Fix `should be =~ /some regex/` / `expect(...).to be =~ /some regex/`.
  Previously, these either failed with a confusing `undefined method
  matches?' for false:FalseClass` error or were no-ops that didn't
  actually verify anything (Myron Marston).
* Add compatibility for diff-lcs 1.2 and relax the version
  constraint (Peter Goldstein).
* Fix DSL-generated matchers to allow multiple instances of the
  same matcher in the same example to have different description
  and failure messages based on the expected value (Myron Marston).
* Prevent `undefined method #split for Array` error when dumping
  the diff of an array of multiline strings (Myron Marston).
* Don't blow up when comparing strings that are in an encoding
  that is not ASCII compatible (Myron Marston).
* Remove confusing "Check the implementation of #==" message
  printed for empty diffs (Myron Marston).

### rspec-mocks 2.13.0

[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.12.2...v2.13.0)

Bug fixes

* Fix bug that caused weird behavior when a method that had
  previously been stubbed with multiple return values (e.g.
  `obj.stub(:foo).and_return(1, 2)`) was later mocked with a
  single return value (e.g. `obj.should_receive(:foo).once.and_return(1)`).
  (Myron Marston)
* Fix bug related to a mock expectation for a method that already had
  multiple stubs with different `with` constraints. Previously, the
  first stub was used, even though it may not have matched the passed
  args. The fix defers this decision until the message is received so
  that the proper stub response can be chosen based on the passed
  arguments (Myron Marston).
* Do not call `nil?` extra times on a mocked object, in case `nil?`
  itself is expected a set number of times (Myron Marston).
* Fix `missing_default_stub_error` message so array args are handled
  properly (Myron Marston).
* Explicitly disallow `any_instance.unstub!` (Ryan Jones).
* Fix `any_instance` stubbing so that it works with `Delegator`
  subclasses (Myron Marston).
* Fix `and_call_original` so that it works with `Delegator` subclasses
  (Myron Marston).
* Fix `any_instance.should_not_receive` when `any_instance.should_receive`
  is used on the same class in the same example. Previously it would
  wrongly report a failure even when the message was not received
  (Myron Marston).

### rspec-rails 2.13.0

[Full Changelog](http://github.com/rspec/rspec-rails/compare/v2.12.2...v2.13.0)

Enhancements

* `be_valid` matcher includes validation error messages. (Tom Scott)
* Adds cucumber scenario showing how to invoke an anonymous controller's
  non-resourceful actions. (Paulo Luis Franchini Casaretto)
* Null template handler is used when views are stubbed. (Daniel Schierbeck)
* The generated `spec_helper.rb` in Rails 4 includes a check for pending
  migrations. (Andy Lindeman)
* Adds `rake spec:features` task. (itzki)
* Rake tasks are automatically generated for each spec/ directory.
  (Rudolf Schmidt)

---

## File: source/blog/2013-04-08-rspec-team-changes.html.md

---
title: RSpec Team Changes
author: Myron Marston
---

The RSpec core team recently expanded to include three new members:

* [Bradley Schaefer](http://www.soulcutter.com/)
* [Jon Rowe](http://jonrowe.co.uk/)
* [Sam Phippen](http://samphippen.com/)

Bradley, Jon and Sam have all been doing great work reviewing pull
requests, triaging issues, fixing bugs, improving RSpec's documentation
and coding new features. We decided it was time to add them to the
team.

Meanwhile, [Chad Humphries](http://spicycode.com/), [Pat
Maddox](http://patmaddox.com/) and [Justin
Ko](https://github.com/justinko) have all chosen to retire from
the team and move on to other things.

Please join me in welcoming Bradley, Jon and Sam, and thanking Chad,
Pat and Justin for all of their contributions to RSpec!

---

## File: source/blog/2013-07-08-rspec-2-14-is-released.html.md

---
title: RSpec 2.14 is released!
author: Myron Marston
---

We've just released RSpec 2.14. It will be the last 2.x feature release
and is a recommended upgrade for all users. We're getting started on
RSpec 3.  I'll be blogging about our plans for RSpec 3 next week, so
check back soon :).

Thanks to all the contributors who helped make this RSpec release happen.

## Notable New Features

### Core: Profiler now profiles example groups, too

RSpec has long had the `--profile` option for dumping the top N
slowest examples at the end. In RSpec 2.14, this has been enhanced
so that it prints the groups with the largest mean example time.
For example, here's the output from using `--profile 5` on rspec-core's
suite:

~~~
Top 5 slowest examples (0.38945 seconds, 10.8% of total time):
  RSpec::Core::Formatters::TextMateFormatter produces HTML identical to the one we designed manually
    0.10471 seconds ./spec/rspec/core/formatters/text_mate_formatter_spec.rb:64
  ::DRbCommandLine --drb-port without RSPEC_DRB environment variable set sets the DRb port
    0.07461 seconds ./spec/rspec/core/drb_command_line_spec.rb:39
  RSpec::Core::Runner#run with --drb or -X and a DRb server is running builds a DRbCommandLine and runs the specs
    0.0744 seconds ./spec/rspec/core/runner_spec.rb:47
  command line when a custom order is configured orders the groups and examples by the provided strategy
    0.06924 seconds ./spec/command_line/order_spec.rb:169
  RSpec::Core::ConfigurationOptions#configure sends pattern before files_or_directories_to_run
    0.06649 seconds ./spec/rspec/core/configuration_options_spec.rb:48

Top 5 slowest example groups:
  RSpec::Core::Formatters::HtmlFormatter
    0.05861 seconds average (0.05861 seconds / 1 example) ./spec/rspec/core/formatters/html_formatter_spec.rb:9
  RSpec::Core::Formatters::TextMateFormatter
    0.05713 seconds average (0.1714 seconds / 3 examples) ./spec/rspec/core/formatters/text_mate_formatter_spec.rb:9
  command line
    0.05218 seconds average (0.31307 seconds / 6 examples) ./spec/command_line/order_spec.rb:3
  ::DRbCommandLine
    0.02016 seconds average (0.16127 seconds / 8 examples) ./spec/rspec/core/drb_command_line_spec.rb:4
  RSpec::Core::Runner
    0.01822 seconds average (0.10931 seconds / 6 examples) ./spec/rspec/core/runner_spec.rb:5
~~~

### Core: New `--warnings` flag to enable Ruby's warning mode

You can now pass the `--warnings` or `-w` flag to enable ruby's warning
mode.

### Core: Shared example groups are scoped to the context they are defined in

Before 2.14, shared example groups were stored in a global hash, could
be defined in any context, and could be used from any context. In 2.14,
this has changed: shared example groups are now scoped to the context
they are defined in. That means you can now do this:

~~~ ruby
describe MySinatraApp1 do
  shared_examples_for "error handling" do
    # some examples would go here
  end

  context 'GET to /foo' do
    include_examples "error handling"
  end

  context 'GET to /bar' do
    include_examples "error handling"
  end
end
~~~

~~~ ruby
describe MySinatraApp2 do
  shared_examples_for "error handling" do
    # some different examples would go here
  end

  context 'GET to /foo' do
    include_examples "error handling"
  end

  context 'GET to /bar' do
    include_examples "error handling"
  end
end
~~~

Here there are two different `"error handling"` shared example
groups, each scoped to (and used from) a different example group.
As demonstrated here, shared example groups are available from
the context they are defined in or from any nested context.
In 2.14, shared example groups declared in sibling contexts
are still available to maintain backwards compatibility,
but will print a deprecation warning. In 3.0, you will not
be able to use a shared example group that was defined in
a sibling context.

### Core: Deprecation output now configurable

RSpec 2.14 has deprecated a number of things in preparation for
removal in 3.0. To help reduce the noisiness of the increased
number of deprecations, there's a new option that can direct
deprecation warnings to a file:

~~~ ruby
# spec_helper.rb
RSpec.configure do |rspec|
  rspec.deprecation_stream = 'log/deprecations.log'
  # or
  rspec.deprecation_stream = File.open("/path/to/file", "w")
end
~~~

Normally, deprecation warnings get printed to `stderr`. When
you configure this, it'll send deprecation warnings to the
configured file instead, and at the end of the spec run
it will print out a message like:

~~~
2 deprecations logged to log/deprecations.log
~~~

### Mocks: New message expectation syntax

In RSpec 2.11, we added a [new syntax to
rspec-expectations](/blog/2012/06/rspecs-new-expectation-syntax)
that removes a reliance on monkey-patching, avoiding certain
kinds of problems related to proxy objects. In RSpec 2.14,
we've extended that same syntax to rspec-mocks:

~~~ ruby
mailer = double("Mailer")

# old syntax:
mailer.stub(:deliver_welcome_email)
mailer.should_receive(:deliver_welcome_email).with(an_instance_of(User))

# new syntax
allow(mailer).to receive(:deliver_welcome_email)
expect(mailer).to receive(:deliver_welcome_email).with(an_instance_of(User))
~~~

For more details, read Sam Phippen's [announcement blog
post](http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/)
from the 2.14.0.rc1 release.

### Mocks: Spies

Joe Ferris from Thoughtbot implemented this new feature. Traditionally,
rspec-mocks has required that you set a message expectation before
the message is received:

~~~ ruby
mailer = double("Mailer")
expect(mailer).to receive(:deliver_welcome_email).with(an_instance_of(User))
UserCreationService.new(mailer).create_user(params)
~~~

In some situations, this ordering feels backwards (particularly if you
try to organize your tests using an arrange/act/assert pattern). Spies
allow you to assert that a message was received after the fact:

~~~ ruby
mailer = double("Mailer", deliver_welcome_email: nil)
UserCreationService.new(mailer).create_user(params)
expect(mailer).to have_received(:deliver_welcome_email).with(an_instance_of(User))
~~~

Note that you first have to stub the message you will later expect
so that rspec-mocks can spy on it. (There's no feasible performant
way for rspec-mocks to automatically spy on all method calls).
Alternately, you can create your test double as a null object,
(using `double().as_null_object`) which has the effect of
auto-spying on all messages sent to that object:

~~~ ruby
mailer = double("Mailer").as_null_object
UserCreationService.new(mailer).create_user(params)
expect(mailer).to have_received(:deliver_welcome_email).with(an_instance_of(User))
~~~

## Docs

### RDoc

* [http://rubydoc.info/gems/rspec-core](http://rubydoc.info/gems/rspec-core)
* [http://rubydoc.info/gems/rspec-expectations](http://rubydoc.info/gems/rspec-expectations)
* [http://rubydoc.info/gems/rspec-mocks](http://rubydoc.info/gems/rspec-mocks)
* [http://rubydoc.info/gems/rspec-rails](http://rubydoc.info/gems/rspec-rails)

### Cucumber Features

* [http://relishapp.com/rspec/rspec-core](http://relishapp.com/rspec/rspec-core)
* [http://relishapp.com/rspec/rspec-expectations](http://relishapp.com/rspec/rspec-expectations)
* [http://relishapp.com/rspec/rspec-mocks](http://relishapp.com/rspec/rspec-mocks)
* [http://relishapp.com/rspec/rspec-rails](http://relishapp.com/rspec/rspec-rails)

## Release Notes

### rspec-core 2.14.0

[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.13.0...v2.14.0)

Enhancements:

* Improved Windows detection inside Git Bash, for better `--color` handling.
* Add profiling of the slowest example groups to `--profile` option.
  The output is sorted by the slowest average example groups.
* Don't show slow examples if there's a failure and both `--fail-fast`
  and `--profile` options are used (Paweł Gościcki).
* Rather than always adding `spec` to the load path, add the configured
  `--default-path` to the load path (which defaults to `spec`). This
  better supports folks who choose to put their specs in a different
  directory (John Feminella).
* Add some logic to test time duration precision. Make it a
  function of time, dropping precision as the time increases. (Aaron Kromer)
* Add new `backtrace_inclusion_patterns` config option. Backtrace lines
  that match one of these patterns will _always_ be included in the
  backtrace, even if they match an exclusion pattern, too (Sam Phippen).
* Support ERB trim mode using the `-` when parsing `.rspec` as ERB
  (Gabor Garami).
* Give a better error message when let and subject are called without a block.
  (Sam Phippen).
* List the precedence of `.rspec-local` in the configuration documentation
  (Sam Phippen)
* Support `{a,b}` shell expansion syntax in `--pattern` option
  (Konstantin Haase).
* Add cucumber documentation for --require command line option
  (Bradley Schaefer)
* Expose configruation options via config:
  * `config.libs` returns the libs configured to be added onto the load path
  * `full_backtrace?` returns the state of the backtrace cleaner
  * `debug?` returns true when the debugger is loaded
  * `line_numbers` returns the line numbers we are filtering by (if any)
  * `full_description` returns the RegExp used to filter descriptions
  (Jon Rowe)
* Add setters for RSpec.world and RSpec.configuration (Alex Soulim)
* Configure ruby's warning behaviour with `--warnings` (Jon Rowe)
* Fix an obscure issue on old versions of `1.8.7` where `Time.dup` wouldn't
  allow access to `Time.now` (Jon Rowe)
* Make `shared_examples_for` context aware, so that keys may be safely reused
  in multiple contexts without colliding. (Jon Rowe)
* Add a configurable `deprecation_stream` (Jon Rowe)
* Publish deprecations through a formatter (David Chelimsky)
* Apply focus to examples defined with `fit` (equivalent of
  `it "description", focus: true`) (Michael de Silva)

Bug fixes:

* Make JSON formatter behave the same when it comes to `--profile` as
  the text formatter (Paweł Gościcki).
* Fix named subjects so that if an inner group defines a method that
  overrides the named method, `subject` still retains the originally
  declared value (Myron Marston).
* Fix random ordering so that it does not cause `rand` in examples in
  nested sibling contexts to return the same value (Max Shytikov).
* Use the new `backtrace_inclusion_patterns` config option to ensure
  that folks who develop code in a directory matching one of the default
  exclusion patterns (e.g. `gems`) still get the normal backtrace
  filtering (Sam Phippen).
* Fix ordering of `before` hooks so that `before` hooks declared in
  `RSpec.configure` run before `before` hooks declared in a shared
  context (Michi Huber and Tejas Dinkar).
* Fix `Example#full_description` so that it gets filled in by the last
  matcher description (as `Example#description` already did) when no
  doc string has been provided (David Chelimsky).
* Fix the memoized methods (`let` and `subject`) leaking `define_method`
  as a `public` method. (Thomas Holmes and Jon Rowe) (#873)
* Fix warnings coming from the test suite. (Pete Higgins)
* Ensure methods defined by `let` take precedence over others
  when there is a name collision (e.g. from an included module).
  (Jon Rowe, Andy Lindeman and Myron Marston)

Deprecations

* Deprecate `Configuration#backtrace_clean_patterns` in favor of
  `Configuration#backtrace_exclusion_patterns` for greater consistency
  and symmetry with new `backtrace_inclusion_patterns` config option
  (Sam Phippen).
* Deprecate `Configuration#requires=` in favor of using ruby's
  `require`. Requires specified by the command line can still be
  accessed by the `Configuration#require` reader. (Bradley Schaefer)
* Deprecate calling `SharedExampleGroups` defined across sibling contexts
  (Jon Rowe)

### rspec-expectations 2.14.0

[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.13.0...v2.14.0)

Enhancements:

* Enhance `yield_control` so that you can specify an exact or relative
  number of times: `expect { }.to yield_control.exactly(3).times`,
  `expect { }.to yield_control.at_least(2).times`, etc (Bartek
  Borkowski).
* Make the differ that is used when an expectation fails better handle arrays
  by splitting each element of the array onto its own line. (Sam Phippen)
* Accept duck-typed strings that respond to `:to_str` as expectation messages.
  (Toby Ovod-Everett)

Bug fixes:

* Fix differ to not raise errors when dealing with differently-encoded
  strings (Jon Rowe).
* Fix `expect(something).to be_within(x).percent_of(y)` where x and y are both
  integers (Sam Phippen).
* Fix `have` matcher to handle the fact that on ruby 2.0,
  `Enumerator#size` may return nil (Kenta Murata).
* Fix `expect { raise s }.to raise_error(s)` where s is an error instance
  on ruby 2.0 (Sam Phippen).
* Fix `expect(object).to raise_error` passing. This now warns the user and
  fails the spec (tomykaira).
* Values that are not matchers use `#inspect`, rather than `#description` for
  documentation output (Andy Lindeman, Sam Phippen).
* Make `expect(a).to be_within(x).percent_of(y)` work with negative y
  (Katsuhiko Nishimra).
* Make the `be_predicate` matcher work as expected used with `expect{...}.to
  change...`  (Sam Phippen).

Deprecations

* Deprecate `expect { }.not_to raise_error(SpecificErrorClass)` or
  `expect { }.not_to raise_error("some specific message")`. Using
  these was prone to hiding failures as they would allow _any other
  error_ to pass. (Sam Phippen and David Chelimsky)

### rspec-mocks 2.14.0

[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.13.0...v2.14.0)

Enhancements:

* Refactor internals so that the mock proxy methods and state are held
  outside of the mocked object rather than inside it. This paves the way
  for future syntax enhancements and removes the need for some hacky
  work arounds for `any_instance` dup'ing and `YAML` serialization,
  among other things. Note that the code now relies upon `__id__`
  returning a unique, consistent value for any object you want to
  mock or stub (Myron Marston).
* Add support for test spies. This allows you to verify a message
  was received afterwards using the `have_received` matcher.
  Note that you must first stub the method or use a null double.
  (Joe Ferris and Joël Quenneville)
* Make `at_least` and `at_most` style receive expectations print that they were
  expecting at least or at most some number of calls, rather than just the
  number of calls given in the expectation (Sam Phippen)
* Make `with` style receive expectations print the args they were expecting, and
  the args that they got (Sam Phippen)
* Fix some warnings seen under ruby 2.0.0p0 (Sam Phippen).
* Add a new `:expect` syntax for message expectations
  (Myron Marston and Sam Phippen).
* Document test spies in the readme. (Adarsh Pandit)
* Add an `array_including` matcher. (Sam Phippen)
* Add a syntax-agnostic API for mocking or stubbing a method. This is
  intended for use by libraries such as rspec-rails that need to mock
  or stub a method, and work regardless of the syntax the user has
  configured (Paul Annesley, Myron Marston and Sam Phippen).

Bug Fixes:

* Fix `any_instance` so that a frozen object can be `dup`'d when methods
  have been stubbed on that type using `any_instance` (Jon Rowe).
* Fix `and_call_original` so that it properly raises an `ArgumentError`
  when the wrong number of args are passed (Jon Rowe).
* Fix `double` on 1.9.2 so you can wrap them in an Array
  using `Array(my_double)` (Jon Rowe).
* Fix `stub_const` and `hide_const` to handle constants that redefine `send`
  (Sam Phippen).
* Fix `Marshal.dump` extension so that it correctly handles nil.
  (Luke Imhoff, Jon Rowe)
* Fix isolation of `allow_message_expectations_on_nil` (Jon Rowe)
* Use inspect to format actual arguments on expectations in failure messages (#280, Ben Langfeld)
* Protect against improperly initialised test doubles (#293) (Joseph Shraibman and Jon Rowe)
* Fix `double` so that it sets up passed stubs correctly regardless of
  the configured syntax (Paul Annesley).
* Allow a block implementation to be used in combination with
  `and_yield`, `and_raise`, `and_return` or `and_throw`. This got fixed
  in 2.13.1 but failed to get merged into master for the 2.14.0.rc1
  release (Myron Marston).
* `Marshal.dump` does not unnecessarily duplicate objects when rspec-mocks has
  not been fully initialized. This could cause errors when using `spork` or
  similar preloading gems (Andy Lindeman).

Deprecations:

* Deprecate `stub` and `mock` as aliases for `double`. `double` is the
  best term for creating a test double, and it reduces confusion to
  have only one term (Michi Huber).
* Deprecate `stub!` and `unstub!` in favor of `stub` and `unstub`
  (Jon Rowe).
* Deprecate `at_least(0).times` and `any_number_of_times` (Michi Huber).

### rspec-rails 2.14.0

Enhancements:

* Preliminarily support Rails 4.1 by updating adapters to support Minitest 5.0.
  (Andy Lindeman)

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)
* `rake stats` runs correctly when spec files exist at the top level of the
  spec/ directory. (Benjamin Fleischer)

---

## File: source/blog/2013-07-15-the-plan-for-rspec-3.html.md

---
title: The Plan for RSpec 3
author: Myron Marston
---

Update: [There's a Japanese translation of
this](http://nilp.hatenablog.com/entry/2013/07/16/131641) available
now.

RSpec 2.0 was released in October 2010. In the nearly three years since
then, we've been able to continually improve RSpec without needing to
make breaking changes, but we've reached a point where RSpec has a fair
bit of cruft stemming from the need to retain backwards
compatibility with older 2.x releases.

[RSpec 2.14](/blog/2013/07/rspec-2-14-is-released)
will be the last RSpec 2 feature release. (We may do some
bug-fix patch releases, though). We're getting started on RSpec 3, and
I'd like to share our thoughts on the direction RSpec will be going.

None of this is set in stone, of course, and ultimately RSpec has been
a successful project because of all of the people who use it. So please
speak up if you have any thoughts about the direction we should take
with RSpec 3!

## What's Being Removed

### No More 1.8.6 and 1.9.1 Support

RSpec 2.x has continued to support Ruby 1.8.6 long after that version
has ceased being supported by the MRI team. As an important piece of
testing infrastructure in the Ruby ecosystem, we've felt that it's
important to allow gem authors to decide when to drop support for
older Ruby versions, and not be forced to do so prematurely because
the test framework they've chosen to use no longer supports one of
the versions they support.

Ruby 1.8.6 and 1.9.1 have not been available on
[Travis](https://travis-ci.org/) for [nearly two
years](https://gist.github.com/michaelklishin/1223640), and
without the safety net of a CI server running our builds
on those versions, it's become extremely difficult to continue
supporting them. In practice, we've really only "semi-supported"
these ruby versions for the last couple years: when users report
issues on these ruby versions, we'll fix them, but we haven't been
expending effort on support beyond that.

And so, the time has come to drop support for these versions. We plan
to continue to support 1.8.7, 1.9.2 and all newer ruby versions on
RSpec 3. Given that 1.8.7 is now legacy, we'll probably be dropping
support for 1.8.7 in RSpec 4, although if/when Travis stops supporting it
before then, we'll only be able to "semi-support" it in the same way
we've been semi-supporting 1.8.6.

### Core: `its` will be moved into an external gem

[I've written about this
before](https://gist.github.com/myronmarston/4503509), so I won't
belabor the point here.  We plan to move `its` out of rspec-core
and into an external gem.

### Expectations: `have(x).items` matchers will be moved into an external gem

RSpec originated in a time before the existence of Cucumber/Gherkin,
and one of its early goals was to express things in natural language
that a project stakeholder could understand.  In those early days,
an expression like `team.should have(9).players` made sense for
the goals of the project. Since then, Cucumber/Gherkin have emerged
as a better alternative for stakeholder-focused tests, and RSpec
is rarely used for that purpose today. The `have(x).items` family
of matchers (including the `have_at_least(x).items` and
`have_at_most(x).items` siblings) are unnecessarily complicated, when a
simple expression like `expect(team.players.size).to eq(9)` works just fine.

We plan to move these matchers out of `rspec-expectations` and into
an external gem.

### Core: No more explicit debugger support

RSpec has long supported a `-d` / `--debug` command line option
for enabling the debugger via the `ruby-debug` gem. However, today
`ruby-debug` is not the only (or even main) debugging gem in use
today. [debugger](https://github.com/cldwalker/debugger) has become
the de-facto standard debugging gem for MRI 1.9.2+, and many developers
prefer to use [pry](http://pryrepl.org/) for debugging. Other
ruby interpreters like Rubinius feature [their own
debugger](http://rubini.us/doc/en/tools/debugger/).

We plan to remove the explicit debugger support in RSpec 3. Besides
removing the command line option, we'll be removing the
[monkey patching of debugger in
Kernel](https://github.com/rspec/rspec-core/blob/v2.13.1/lib/rspec/core/extensions/kernel.rb)
when ruby-debug is not loaded, so you will get a `NoMethodError`
from `debugger` when a debugger is not loaded.

If you want to continue to load the debugger using a command line option,
you can use the require flag (`-r`), using an option like `-rdebugger`.

### Core: No more RCov integration

`RSpec::Core::RakeTask` has had some [RCov
options](https://github.com/rspec/rspec-core/blob/v2.13.1/lib/rspec/core/rake_task.rb#L65-L84)
for a long time. RCov only works with MRI 1.8, and today
most ruby developers use
[SimpleCov](https://github.com/colszowka/simplecov) for their code
coverage needs. SimpleCov integrates with RSpec (or any test framework)
very simply, with no explicit support needed from within RSpec itself.

### Core: Autotest integration will be moved into an external gem

Autotest used to be the primary ruby continuous test runner.
These days, [guard](https://github.com/guard/guard) seems to
be the more popular choice, and there's no reason that RSpec's
Autotest integration needs to remain in rspec-core.

### Core: TextMate formatter will be moved into the TextMate bundle

For many years, TextMate was the most popular text editor used by
ruby developers. RSpec has had a [TextMate-specific
formatter](https://github.com/rspec/rspec-core/blob/v2.13.1/lib/rspec/core/formatters/text_mate_formatter.rb)
for many years.  These days, [TextMate isn't nearly as popular
among ruby developers as it used to
be](http://survey.hamptoncatlin.com/survey/stats#question_6), and
there's no compelling reason for the TextMate formatter
to remain in rspec-core.

### Lots of Deprecations

RSpec 2.14 includes many things that have been deprecated
over the last couple of years. We plan to remove nearly all of the
deprecated APIs and features.

### What about the old expectation/mock syntax?

[RSpec 2.11
introduced](/blog/2012/06/rspecs-new-expectation-syntax)
a new `expect`-based syntax for rspec-expectations.
[In RSpec
2.14](http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/),
we updated rspec-mocks to use a similar syntax. Since
introducing the new syntax, I've received a number of questions
about how soon we will be deprecating or removing the old
`should`-based syntax.

While I won't say "never" (who knows what the future holds?),
we don't have any current plans to ever remove the old syntax.
Users have invested in code that uses the old syntax for many
years, and while we recommend using the new syntax (particularly
for new projects), we'd be doing users a disservice to remove
the old syntax anytime soon. It's also not a significant
maintenance burden.

For RSpec 3, we considered the idea of disabling the old syntax
by default, forcing users to opt-in to use it.  However, I think
that doing so would be a disservice to new users who are coming
to RSpec through a less-than-current tutorial. Getting a `NoMethodError`
for an example copied from a tutorial can be very frustrating
to someone trying RSpec for the first time. Experienced users
can easily disable the old syntax, whereas new users aren't
likely to have enough RSpec knowledge to know to enable
the old syntax used by their tutorial.

That said, we do want to encourage people to switch to
the new syntax, so we plan to make RSpec 3
print a warning on first usage of any the old syntax
methods (`should`, `should_not`, `should_receive`, etc)
_unless the `should` syntax has been explicitly enabled_.
This should nudge folks towards the new syntax while keeping
RSpec friendly to new users and will pave the way for
the old syntax to be disabled by default in RSpec 4.

## What's New

### Zero Monkey Patching Mode!

Historically, RSpec has extensively used monkey patching
to create its readable syntax, adding methods like `describe`,
`shared_examples_for`, `shared_context`,
`should`, `should_not`, `should_receive`, `should_not_receive`
and `stub` to every object. In the last few 2.x releases, we've
worked towards reducing the amount of monkey patching done by RSpec:

* As of rspec-core 2.11, `describe` is no longer added to every
  object. Instead, it is only added to the top-level `main` object
  and to `Module` (so that it is available from within classes
  and modules).
* In rspec-expectations 2.11, we added the `expect` syntax and
  provided a config option to disable the `should` syntax -- which
  removes `should` and `should_not` from every object.
* As of rspec-core 2.12, `shared_examples_for` and `shared_context`,
  are no longer added to every object. As with `describe`, they are
  only added to the top-level `main` object and to `Module`.
* In rspec-mocks 2.14, we updated `rspec-mocks` to support an
  `expect`-based syntax as well, and provided a config option
  to disable the old mocking syntax -- which removes `should_receive`,
  `should_not_receive` and `stub` from every object.

As discussed above, we'll be removing RSpec's monkey-patched
`Kernel#debugger` in 3.0. We're also planning to provide a
config option to remove the monkey patching of the top-level
DSL methods (`describe`, `shared_examples_for`, etc) onto
`main` and `Module`, instead requiring you to prefix these
methods with `RSpec.`:

~~~ ruby
RSpec.describe MyClass do
  # Within an example group you'll still be able to use
  # a bare `describe`:
  describe "#some_method" do
  end

  # And you'll be able to use a bare `shared_examples_for`:
  shared_examples_for "something" do
  end
end

RSpec.shared_examples_for "some behavior" do
end
~~~

The net result will be a set of config options (one for
`rspec-expectations`, one for `rspec-mocks` and one for `rspec-core`), that
will provide a zero-monkey-patching mode for RSpec. (We may also
provide a single unified config option that sets all three).

We plan for these config options to become the defaults in RSpec 4.0,
so that RSpec 4.0 will have zero monkey patching out of the box.

### Mocks: Test double interface verification

It's unfortunately been very easy to let your test doubles
get out of sync with the real interfaces they are doubling.
When you rename a method, or change the number of arguments
a method expects, it's easy to forget to update the test doubles
you are using as standins for the changed class.

I've long been a fan of
[rspec-fire's](https://github.com/xaviershay/rspec-fire) approach
to solving this problem.  I plan to port a version of it to rspec-mocks.

Take a look at the [github
issue](https://github.com/rspec/rspec-mocks/issues/227#issuecomment-19143955)
where we are discussing this for the full details (the API and semantics
of this feature are certainly not set in stone yet, so please voice your
thoughts on that ticket!)

### Expectations: Fully composable matchers

In RSpec 2.13, we [added
support](/blog/2013/02/rspec-2-13-is-released#_matcher_can_accept_a_list_of_matchers)
for the `include` matcher to accept a list of matchers to match against.
This kind of composability is quite useful and we plan to extend
it to all matchers in RSpec 3. For example, you could use an expression
like:

~~~ ruby
expect { |b|
  some_object.do_something(&b)
}.to yield_with_args(include(match(/foo/), match(/bar/)))
~~~

This expresses a detailed expectation: "I expect
`some_object.do_something` to yield with a collection that
includes a string matching `/foo/` and a string matching `/bar/`".

We're also considering adding matcher aliases that read better when
composed in this fashion, so that you could write this as:

~~~ ruby
expect { |b|
  some_object.do_something(&b)
}.to yield_with_args(a_collection_including(a_string_matching(/foo/),
                                            a_string_matching(/bar/)))
~~~

For more details, or to weigh in on this issue, take a look at the
[github issue](https://github.com/rspec/rspec-expectations/issues/280).

### Core: Formatter API improvements

The current API for notifying formatters of test suite progress has proved to
be a bit inflexible when it comes to adding in new notifications and changing
existing notifications.  We're planning to change it in a couple ways:

* Rather than requiring that all formatters implement all notification methods,
  formatters will be able to subscribe to specific notifications. This will
  allow you to implement the minimum set your formatter needs, and will allow
  us to add new notifications without worrying about breaking existing formatters.
* Notification arguments will change from an ordered list of arguments
  to a single value object, which will allow us to easily add additional data
  to specific notifications without changing the method signature.

These changes will allow us to make further improvements that we have been unable
to make in the 2.x releases. We also plan to provide a compatibility layer in
RSpec 3 that wraps formatters written against the old API and adapts
them to the new API so that users can more easily upgrade when they rely
upon old formatters.

For more details, take a look at the [github
issue](https://github.com/rspec/rspec-core/issues/944).

### Core: DSL methods will yield the example

In RSpec 2, the current running example is exposed as `example`.
It can be used to [access the example's
metadata](https://relishapp.com/rspec/rspec-core/v/2-14/docs/metadata/user-defined-metadata#define-group-metadata-using-a-hash).
This has occasionally [caused
problems](https://github.com/rspec/rspec-core/issues/663)
when users inadvertently define their own `example` method. In RSpec 3,
we're removing the `example` method, opting to yield the example from
each DSL method that runs in the context of an example:

~~~ ruby
describe MyClass do
  before(:each) { |example| }
  subject       { |ex| }
  let(:user)    { |ex| User.find(ex.metadata[:user_id]) }

  # before(:all) will NOT yield an example

  it "can access the current example using a block local" do |example|
    # do something with `example`
  end
end
~~~

We're aware that this may cause upgrade headaches for users who
rely on gems that use the `example` API (such as Capybara).
We're discussing ways to make the upgrade smoother, both for users
of gem authors. For more information, see the [github
issue](https://github.com/rspec/rspec-core/pull/666).

### Expectations: Matcher protocol and custom matcher API changes

While RSpec has been moving away from its `should`-based syntax,
the matcher protocol and custom matcher API have not changed
accordingly. The matcher protocol still relies upon methods like
`failure_message_for_should` and `failure_message_for_should_not`,
and the custom matcher API has methods like `match_for_should`
and `match_for_should_not`.

In RSpec 3, we'd like to change the matcher protocol and custom matcher
API to no longer speak in terms of `should` while still retaining
a backwards compatibility layer so that existing matchers will
continue to work, with the plan to remove that compatibility
layer in RSpec 4. We're not sure what the new APIs will be yet; if
you have thoughts, please [chime in on the github
issue](https://github.com/rspec/rspec-expectations/issues/270).

### Mocks: `any_instance` block implementations will yield the receiver

When stubbing a method using `any_instance` you can pass a block
implementation just like a normal stub. However, if you wanted to
access the receiver (i.e. the instance receiving the message) in
the block, there was no way to accomplish this.  In RSpec 3, we're
correcting this oversight, and the receiver will be yielded as
the first block argument:

~~~ ruby
allow_any_instance_of(User).to receive(:age) do |user|
  ((Date.today - user.birthdate) / 365).floor
end
~~~

For backwards compatibility, we'll be adding a config option to disable
this behavior.

## The Upgrade Path

Even though RSpec 3.0 will be a major release that allows
us to make intentional breaking changes for the first time since 2010,
it's important to us that the upgrade path for existing
test suites be as easy as possible. To that end, we're planning
a 2.99 release that will exist purely to help users upgrade.
Here's what we have in mind:

* RSpec 2.99 will be RSpec 2.14 plus some extra deprectation warnings
  for things that will be removed in 3.0.
* You should be able to take your existing RSpec 2.x test suite and
  upgrade to 2.99 _without_ needing to make any changes.
* RSpec 2.99 will give you deprecation notices for anything we're
  removing or somehow breaking in 3.0. You should address those
  warnings. Once you're warning-free on 2.99, you should be able
  to upgrade to 3.0 without needing to make any further changes.

The 2.99 release will be an important step that shouldn't be skipped
in the upgrade process. It'll give you an upgrade checklist that
is specifically tailored to _your_ test suite's usage of RSpec,
giving you a much simpler and more efficient way to upgrade than
combing through changelogs trying to figure out what all is changing
in RSpec 3.

## The Development and Release Plan

We've already began working on RSpec 3 in the master branches of
each of the RSpec repos. We also have a 2-14-maintenance branch
for 2.14 changes (i.e. for possible patch releases)
and a 2-99-maintenance branch for the changes
that will be going in to 2.99. We're planning to do multiple
release candidates (and potentially some beta releases) as we
make progress towards the final 3.0 release.

I won't venture a guess for when we might release RSpec 3.
Experience has taught me that software release date estimates
are always wrong :(.

## "How can I help?"

The current RSpec core team ([David](https://twitter.com/dchelimsky),
[Andy](https://twitter.com/alindeman), [Jon](https://twitter.com/JonRowe),
[Sam](https://twitter.com/samphippen), [Bradley](https://twitter.com/soulcutter)
and [myself](https://twitter.com/myronmarston)) will be driving the work
for the 3.0 release...but as always, we love to get help from the community.
Here are some specific ways you can help out:

* As mentioned above, we plan to extract some of RSpec's functionality
  into an external gem (`its`, `have` matchers and the autotest integration).
  It would be great to find folks in the community who can step forward
  and take over maintenance (and maybe even do the initial extraction,
  if you're so inclined) for these gems.
* We value community feedback about the direction RSpec is going, so please
  comment on the issues I've linked to above (and any other issues, really --
  there will be more in RSpec 3 than I've covered here!)
  if you have thoughts or ideas.
* If you'd like to help contribute code to RSpec, that's great! However,
  during this period, there's going to be more churn than usual in the
  codebases of the various RSpec gems, creating more merge conflicts
  with pull requests, and making it more difficult for us to integrate
  contributions from users. So, if you want to contribute, please get
  in touch (either by commenting on github issues and/or chatting with
  us on the #rspec channel on irc.freenode.net) before putting extensive
  effort into a PR. A little bit of communication up front will go a long
  way towards making it easy for us to integrate your contribution.
* One of the most important ways you can help is to try out out the
  pre-release versions of 2.99 and 3.0 and give us feedback. Stay tuned
  for release announcements.
* [rspec.info](http://rspec.info/) is badly in need of a refresh, and it
  would be great to launch a new version of that site in tandem with the
  release of RSpec 3.  However, it's very hard for the RSpec core team to
  find time to work on the website, and most of us focus more on backend
  than frontend dev. It would be great if some community members would
  step forward and help in this area!

---

## File: source/blog/2013-11-08-rspec-2-99-and-3-0-betas-have-been-released.html.md

---
title: RSpec 2.99 and 3.0 betas have been released!
author: Myron Marston
---

The RSpec team has just released RSpec 3.0.0.beta1 -- the first RSpec 3 pre-release!
Along with that, we've released 2.99.0.beta1, which is intended to help with
the upgrade process.

I'd like to thank all the contributors, and especially the core team
([Andy](https://twitter.com/alindeman), [Bradley](https://twitter.com/soulcutter),
[Jon](https://twitter.com/JonRowe), [Sam](https://twitter.com/samphippen) and
[Xavier](https://twitter.com/xshay)) for making this release happen.

I don't have the energy right now to write up a full "What's new in RSpec 3"
blog post, but we've mostly been making changes according to what
we [previously announced for RSpec 3](/blog/2013/07/the-plan-for-rspec-3).
The detailed release notes are below to fill you in on the details for
these releases. We'll be following up with other blog posts in the
future discussing the new features in depth.

## The Upgrade Process

RSpec 3 includes many breaking changes, but our hope is to make this
the smoothest major-version gem upgrade you've ever done. To assist
with that process, we've been developing RSpec 2.99 in tandem with
RSpec 3.  Every time we make a breaking change in the master branch
for 3.0, we've been adding a corresponding deprecation to 2.99.  This
isn't just for APIs that have been removed; it's also for slight changes
in edge-case semantics (in order to make RSpec more consistent) that
some projects may rely on. Rather than just giving you a generic
upgrade document that describes _all_ of the breaking changes
(including many that affect very few users!), RSpec 2.99 gives you
a detailed upgrade checklist.

In addition, [Yuji Nakayama](https://twitter.com/nkym37) has been developing
[transpec](https://github.com/yujinakayama/transpec) -- an absolutely amazing
tool that can automatically upgrade most RSpec suites. I've tried it on a
couple projects and I've been _amazed_ at how well it works.

Here's the general approach I recommend for upgrading a project to RSpec 3:

1. Ensure your test suite is already green on whatever RSpec 2.x version
   you're already using.
2. Install RSpec 2.99.0.beta1 (or whatever the latest 2.99 release is
   when you go through this process).
3. Run your test suite and ensure it's still green. (It should be, but
   we may have made a mistake -- if it breaks anything, please report
   a bug!). Now would be a good time to commit.
4. You'll notice a bunch of deprecation warnings printed off at the
   end of the spec run. These may be truncated since we don't to
   spam you with the same deprecation warning over and over again. To
   get the full list of deprecations, you can pipe them into a file
   by setting the `config.deprecation_stream = 'rspec.log'` option.
5. If you want to understand all of what is being deprecated, it's a
   good idea to read through the deprecation messages.  In some cases,
   you have choices -- such as continuing to use the `have` collection
   cardinality matchers via the extracted
   [rspec-collection_matchers](https://github.com/rspec/rspec-collection_matchers)
   gem, or by rewriting the expectation expression to something like
   `expect(list.size).to eq(3)`.
6. `gem install transpec` (Note that this need not go into your
   `Gemfile`: you run `transpec` as a standalone executable
    outside the context of your bundle).
7. Run transpec on your project. Check `transpec --help` or
   [the README](https://github.com/yujinakayama/transpec#transpec)
   for a full list of options.
8. Run the test suite (it should still be green but it's always good to check!)
   and commit.
9. If there are any remaining deprecation warnings (transpec doesn't quite handle
   all of the warnings you may get), deal with them.
9. Once you've got a deprecation-free test suite running against RSpec 2.99,
   you're ready to upgrade to RSpec 3. Install RSpec 3.0.0.beta1
   (or whatever the latest 3.x release is when you go through this process).
10. Run your test suite. It should still be green. If anything fails, please
    open a GitHub issue -- we consider it a bug[^foot_1]!
11. Commit and enjoy using the latest RSpec release!

## What's Next

While we've made significant progress on RSpec 3, we're not done yet.
We have more to do. (We haven't gotten to everything we've planned.)
We take [SemVer](http://semver.org/) seriously, and this is the first
opportunity we've had in years to clean out old cruft, so we want to
take full advantage of it :). We hope to release an RC in the next
few months, with a final release shortly after that.

## Release Notes

### rspec-core 2.99.0.beta1

[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.14.7...v2.99.0.beta1)

Enhancements:

* Block-based DSL methods that run in the context of an example
  (`it`, `before(:each)`, `after(:each)`, `let` and `subject`)
  now yield the example as a block argument. (David Chelimsky)
* Warn when the name of more than one example group is submitted to
  `include_examples` and it's aliases. (David Chelimsky)
* Add `expose_current_running_example_as` config option for
  use during the upgrade process when external gems use the
  deprecated `RSpec::Core::ExampleGroup#example` and
  `RSpec::Core::ExampleGroup#running_example` methods. (Myron Marston)
* Limit spamminess of deprecation messages. (Bradley Schaefer, Loren Segal)
* Add `config.raise_errors_for_deprecations!` option, which turns
  deprecations warnings into errors to surface the full backtrace
  of the call site. (Myron Marston)

Deprecations:

* Deprecate `RSpec::Core::ExampleGroup#example` and
  `RSpec::Core::ExampleGroup#running_example` methods. If you need
  access to the example (e.g. to get its metadata), use a block argument
  instead. (David Chelimsky)
* Deprecate use of `autotest/rspec2` in favour of `rspec-autotest`. (Jon Rowe)
* Deprecate RSpec's built-in debugger support. Use a CLI option like
  `-rruby-debug` (for the ruby-debug gem) or `-rdebugger` (for the
  debugger gem) instead. (Myron Marston)
* Deprecate `config.treat_symbols_as_metadata_keys_with_true_values = false`.
  RSpec 3 will not support having this option set to `false`. (Myron Marston)
* Deprecate accessing a `let` or `subject` declaration in
  a `after(:all)` hook. (Myron Marston, Jon Rowe)
* Deprecate built-in `its` usage in favor of `rspec-its` gem due to planned
  removal in RSpec 3. (Peter Alfvin)
* Deprecate `RSpec::Core::PendingExampleFixedError` in favor of
  `RSpec::Core::Pending::PendingExampleFixedError`. (Myron Marston)
* Deprecate `RSpec::Core::Configuration#out` and
  `RSpec::Core::Configuration#output` in favor of
  `RSpec::Core::Configuration#output_stream`. (Myron Marston)
* Each of the following are deprecated in favor of
  `register_ordering(:global)` (Myron Marston):
  * `RSpec::Core::Configuration#order_examples`
  * `RSpec::Core::Configuration#order_groups`
  * `RSpec::Core::Configuration#order_groups_and_examples`
* These are deprecated with no replacement because in RSpec 3
  ordering is a property of individual example groups rather than
  just a global property of the entire test suite (Myron Marston):
  * `RSpec::Core::Configuration#order`
  * `RSpec::Core::Configuration#randomize?`
  * `--order default` is deprecated in favor of `--order defined`

### rspec-core 3.0.0.beta1

[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.99.0.beta1...v3.0.0.beta1)

Breaking Changes:

* Remove explicit support for 1.8.6. (Jon Rowe)
* Remove `RSpec::Core::ExampleGroup#example` and
  `RSpec::Core::ExampleGroup#running_example` methods. If you need
  access to the example (e.g. to get its metadata), use a block arg
  instead. (David Chelimsky)
* Remove `TextMateFormatter`, it has been moved to `rspec-tmbundle`.
  (Aaron Kromer)
* Remove RCov integration. (Jon Rowe)
* Remove deprecated support for RSpec 1 constructs (Myron Marston):
  * The `Spec` and `Rspec` constants (rather than `RSpec`).
  * `Spec::Runner.configure` rather than `RSpec.configure`.
  * `Rake::SpecTask` rather than `RSpec::Core::RakeTask`.
* Remove deprecated support for `share_as`. (Myron Marston)
* Remove `--debug` option (and corresponding option on
  `RSpec::Core::Configuration`). Instead, use `-r<debugger gem name>` to
  load whichever debugger gem you wish to use (e.g. `ruby-debug`,
  `debugger`, or `pry`). (Myron Marston)
* Extract Autotest support to a seperate gem. (Jon Rowe)
* Raise an error when a `let` or `subject` declaration is
  accessed in a `before(:all)` or `after(:all)` hook. (Myron Marston)
* Extract `its` support to a separate gem. (Peter Alfvin)
* Disallow use of a shared example group from sibling contexts, making them
  fully isolated. 2.14 and 2.99 allowed this but printed a deprecation warning.
  (Jon Rowe)
* Remove `RSpec::Core::Configuration#output` and
  `RSpec::Core::Configuration#out` aliases of
  `RSpec::Core::Configuration#output_stream`. (Myron Marston)

Enhancements:

* Replace unmaintained syntax gem with coderay gem. (Xavier Shay)
* Times in profile output are now bold instead of `failure_color`.
  (Matthew Boedicker)
* Add `--no-fail-fast` command line option. (Gonzalo Rodríguez-Baltanás Díaz)
* Runner now considers the local system ip address when running under Drb.
  (Adrian CB)
* JsonFormatter now includes `--profile` information. (Alex / @MasterLambaster)
* Always treat symbols passed as metadata args as hash
  keys with true values. RSpec 2 supported this with the
  `treat_symbols_as_metadata_keys_with_true_values` but
  now this behavior is always enabled. (Myron Marston)
* Add `--dry-run` option, which prints the formatter output
  of your suite without running any examples or hooks.
  (Thomas Stratmann, Myron Marston)
* Document the configuration options and default values in the `spec_helper.rb`
  file that is generated by RSpec. (Parker Selbert)
* Give generated example group classes a friendly name derived
  from the docstring, rather than something like "Nested_2".
  (Myron Marston)
* Avoid affecting randomization of user code when shuffling
  examples so that users can count on their own seeds
  working. (Travis Herrick)

Deprecations:

* `treat_symbols_as_metadata_keys_with_true_values` is deprecated and no
  longer has an affect now that the behavior it enabled is always
  enabled. (Myron Marston)

### rspec-mocks 2.99.0.beta1

[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.14.4...v2.99.0.beta1)

Deprecations:

* Expecting to use lambdas or other strong arity implementations for stub
  methods with mis-matched arity is deprecated and support for them will be
  removed in 3.0. Either provide the right amount of arguments or use a weak
  arity implementation (methods with splats or procs). (Jon Rowe)
* Using the same test double instance in multiple examples is deprecated. Test
  doubles are only meant to live for one example. The mocks and stubs have
  always been reset between examples; however, in 2.x the `as_null_object`
  state was not reset and some users relied on this to have a null object
  double that is used for many examples. This behavior will be removed in 3.0.
  (Myron Marston)
* Print a detailed warning when an `any_instance` implementation block is used
  when the new `yield_receiver_to_any_instance_implementation_blocks` config
  option is not explicitly set, as RSpec 3.0 will default to enabling this new
  feature. (Sam Phippen)

Enhancements:

* Add a config option to yield the receiver to `any_instance` implementation
  blocks. (Sam Phippen)

### rspec-mocks 3.0.0.beta1
[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.99.0.beta1...v3.0.0.beta1)

Breaking Changes:

* Raise an explicit error if `should_not_receive(...).and_return` is used. (Sam
  Phippen)
* Remove 1.8.6 workarounds. (Jon Rowe)
* Remove `stub!` and `unstub!`. (Sam Phippen)
* Remove `mock(name, methods)` and `stub(name, methods)`, leaving
  `double(name, methods)` for creating test doubles. (Sam Phippen, Michi Huber)
* Remove `any_number_of_times` since `should_receive(:msg).any_number_of_times`
  is really a stub in a mock's clothing. (Sam Phippen)
* Remove support for re-using the same null-object test double in multiple
  examples.  Test doubles are designed to only live for one example.
  (Myron Marston)
* Make `at_least(0)` raise an error. (Sam Phippen)
* Remove support for `require 'spec/mocks'` which had been kept
  in place for backwards compatibility with RSpec 1. (Myron Marston)
* Blocks provided to `with` are always used as implementation. (Xavier Shay)
* The config option (added in 2.99) to yield the receiver to
  `any_instance` implementation blocks now defaults to "on". (Sam Phippen)

Enhancements:

* Allow the `have_received` matcher to use a block to set further expectations
  on arguments. (Tim Cowlishaw)
* Provide `instance_double` and `class_double` to create verifying doubles,
  ported from `rspec-fire`. (Xavier Shay)
* `as_null_object` on a verifying double only responds to defined methods.
  (Xavier Shay)
* Provide `object_double` to create verified doubles of specific object
  instances. (Xavier Shay)
* Provide `verify_partial_doubles` configuration that provides `object_double`
  like verification behaviour on partial mocks. (Xavier Shay)
* Improved performance of double creation, particularly those with many
  attributes. (Xavier Shay)
* Default value of `transfer_nested_constants` option for constant stubbing can
  be configured. (Xavier Shay)
* Messages can be allowed or expected on in bulk via
  `receive_messages(:message => :value)`. (Jon Rowe)
* `allow(Klass.any_instance)` and `expect(Klass.any_instance)` now print a
  warning. This is usually a mistake, and users usually want
  `allow_any_instance_of` or `expect_any_instance_of` instead. (Sam Phippen)
* `instance_double` and `class_double` raise `ArgumentError` if the underlying
  module is loaded and the arity of the method being invoked does not match the
  arity of the method as it is actually implemented. (Andy Lindeman)
* Spies can now check their invocation ordering is correct. (Jon Rowe)

Deprecations:

* Using the old `:should` syntax without explicitly configuring it
  is deprecated. It will continue to work but will emit a deprecation
  warning in RSpec 3 if you do not explicitly enable it. (Sam Phippen)

Bug Fixes:

* Fix `and_call_original` to handle a complex edge case involving
  singleton class ancestors. (Marc-André Lafortune, Myron Marston)
* When generating an error message for unexpected arguments,
  use `#inspect` rather than `#description` if `#description`
  returns `nil` or `''` so that you still get a useful message.
  (Nick DeLuca)

### rspec-expectations 2.99.0.beta1

[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.14.4...v2.99.0.beta1)

Deprecations:

* Deprecate `have`, `have_at_least` and `have_at_most`. You can continue using those
  matchers through https://github.com/rspec/rspec-collection_matchers, or
  you can rewrite your expectations with something like
  `expect(your_object.size).to eq(num)`. (Hugo Baraúna)
* Deprecate `be_xyz` predicate matcher when `xyz?` is a private method.
  (Jon Rowe)
* Deprecate `be_true`/`be_false` in favour of `be_truthy`/`be_falsey`
  (for Ruby's conditional semantics) or `be true`/`be false`
  (for exact equality). (Sam Phippen)
* Deprecate calling helper methods from a custom matcher with the wrong
  scope. (Myron Marston)
  * `def self.foo` / `extend Helper` can be used to add macro methods
    (e.g. methods that call the custom matcher DSL methods), but should
    not be used to define helper methods called from within the DSL
    blocks.
  * `def foo` / `include Helper` is the opposite: it's for helper methods
    callable from within a DSL block, but not for defining macros.
  * RSpec 2.x allowed helper methods defined either way to be used for
    either purpose, but RSpec 3.0 will not.

### rspec-expectations 3.0.0.beta1

[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.99.0.beta1...v3.0.0.beta1)

Breaking Changes:

* Remove explicit support for 1.8.6. (Jon Rowe)
* Remove the deprecated `be_close` matcher, preferring `be_within` instead.
  (Sam Phippen)
* Rename `be_true` and `be_false` to `be_truthy` and `be_falsey`. (Sam Phippen)
* Make `expect { }.to_not raise_error(SomeSpecificClass, message)`,
       `expect { }.to_not raise_error(SomeSpecificClass)` and
       `expect { }.to_not raise_error(message)` invalid, since they are prone
  to hiding failures. Instead, use `expect { }.to_not raise_error` (with no
  args). (Sam Phippen)
* Within `RSpec::Matchers.define` blocks, helper methods made available
  either via `def self.helper` or `extend HelperModule` are no longer
  available to the `match` block (or any of the others). Instead
  `include` your helper module and define the helper method as an
  instance method. (Myron Marston)

Enhancements:

* Support `do..end` style block with `raise_error` matcher. (Yuji Nakayama)
* Rewrote custom matcher DSL to simplify its implementation and solve a
  few issues. (Myron Marston)
* Allow early `return` from within custom matcher DSL blocks. (Myron
  Marston)
* The custom matcher DSL's `chain` can now accept a block. (Myron
  Marston)
* Support setting an expectation on a `raise_error` matcher via a chained
  `with_message` method call. (Sam Phippen)

Bug Fixes:

* Allow `include` and `match` matchers to be used from within a
  DSL-defined custom matcher's `match` block. (Myron Marston)

Deprecations:

 * Using the old `:should` syntax without explicitly configuring it is deprecated.
   It will continue to work but will emit a deprecation warning in RSpec 3 if
   you do not explicitly enable it. (Sam Phippen)

### rspec-rails 2.99.0.beta1

[Full Changelog](http://github.com/rspec/rspec-rails/compare/v2.14.0...v2.99.0.beta1)

Deprecations:

* Deprecates autotest integration in favor of the `rspec-autotest` gem. (Andy
  Lindeman)

Enhancements:

* Supports Rails 4.1 and Minitest 5. (Patrick Van Stee)

Bug Fixes:

* Fixes "warning: instance variable @orig\_routes not initialized" raised by
  controller specs when `--warnings` are enabled. (Andy Lindeman)
* Where possible, check against the version of ActiveRecord, rather than
  Rails. It is possible to use some of rspec-rails without all of Rails.
  (Darryl Pogue)
* Explicitly depends on `activemodel`. This allows libraries that do not bring
  in all of `rails` to use `rspec-rails`. (John Firebaugh)

### rspec-rails 3.0.0.beta1

[Full Changelog](http://github.com/rspec/rspec-rails/compare/v2.99.0.beta1...v3.0.0.beta1)

Breaking Changes:

* Extracts `autotest` and `autotest-rails` support to `rspec-autotest` gem.
  (Andy Lindeman)

[^foot_1]: There is one caveat to that, though: we only consider it a bug to the extent that your test suite uses the RSpec APIs as they are documented. The dynamic nature of Ruby makes it possible to use RSpec in ways that we can't support.

---

## File: source/blog/2014-01-14-new-in-rspec-3-composable-matchers.html.md

---
title: "New in RSpec 3: Composable Matchers"
author: Myron Marston
---

One of RSpec 3's big new features is shipping 3.0.0.beta2: composable
matchers. This feature supports more powerful, less brittle
expectations, and opens up new possibilities.

## An Example

In RSpec 2.x, I've written code like this on many occassions:

~~~ ruby
# background_worker.rb
class BackgroundWorker
  attr_reader :queue

  def initialize
    @queue = []
  end

  def enqueue(job_data)
    queue << job_data.merge(:enqueued_at => Time.now)
  end
end
~~~

~~~ ruby
# background_worker_spec.rb
describe BackgroundWorker do
  it 'puts enqueued jobs onto the queue in order' do
    worker = BackgroundWorker.new
    worker.enqueue(:klass => "Class1", :id => 37)
    worker.enqueue(:klass => "Class2", :id => 42)

    expect(worker.queue.size).to eq(2)
    expect(worker.queue[0]).to include(:klass => "Class1", :id => 37)
    expect(worker.queue[1]).to include(:klass => "Class2", :id => 42)
  end
end
~~~

In RSpec 3, composable matchers allow you to pass matchers as arguments
(or nested within data structures passed as arguments) to other matchers
allowing you to simplify specs like these:

~~~ ruby
# background_worker_spec.rb
describe BackgroundWorker do
  it 'puts enqueued jobs onto the queue in order' do
    worker = BackgroundWorker.new
    worker.enqueue(:klass => "Class1", :id => 37)
    worker.enqueue(:klass => "Class2", :id => 42)

    expect(worker.queue).to match [
      a_hash_including(:klass => "Class1", :id => 37),
      a_hash_including(:klass => "Class2", :id => 42)
    ]
  end
end
~~~

We've made sure the failure messages read well for cases like these,
opting to use the `description` of the provided matcher rather than
the `inspect` output.  For example, if we "break" the implementation
tested by this spec by commenting out the `queue << ...` line, it fails
with:

~~~
1) BackgroundWorker puts enqueued jobs onto the queue in order
   Failure/Error: expect(worker.queue).to match [
     expected [] to match [(a hash including {:klass => "Class1", :id => 37}), (a hash including {:klass => "Class2", :id => 42})]
     Diff:
     @@ -1,3 +1,2 @@
     -[(a hash including {:klass => "Class1", :id => 37}),
     - (a hash including {:klass => "Class2", :id => 42})]
     +[]

   # ./spec/background_worker_spec.rb:19:in `block (2 levels) in <top (required)>'
~~~

## Matcher aliases

As you may have noticed, the example above uses `a_hash_including`
in place of `include`. RSpec 3 provides similar aliases for all of the
built-in matchers that read better grammatically and provide a
better failure message.

For example, compare this expectation and failure message:

~~~
x = "a"
expect { }.to change { x }.from start_with("a")
~~~
~~~
expected result to have changed from start with "a", but did not change
~~~

...to:

~~~ ruby
x = "a"
expect { }.to change { x }.from a_string_starting_with("a")
~~~
~~~
expected result to have changed from a string starting with "a",
but did not change
~~~

While `a_string_starting_with` is more verbose than `start_with`, it
produces a failure message that actually reads well, so you don't trip
over odd grammatical constructs. We've provided one or more similar
aliases for all of RSpec's built-in matchers. We've tried to use
consistent phrasing (generally "a \[type of object\] \[verb\]ing") so
they are easy to guess. You'll see many examples below, and the RSpec
3 docs will have a full list.

There's also a public API that makes it trivial to define your own aliases
(either for RSpec's built in matchers or for a custom matcher). Here's
the bit of code in rspec-expectations that provides the
`a_string_starting_with` alias of `start_with`:

~~~ ruby
RSpec::Matchers.alias_matcher :a_string_starting_with, :start_with
~~~

## Compound Matcher Expressions

[Eloy Espinaco](https://github.com/eloyesp) contributed a new feature
that provides another way of combining matchers: compound `and` and `or`
matcher expressions. For example, rather than writing this:

~~~ ruby
expect(alphabet).to start_with("a")
expect(alphabet).to end_with("z")
~~~

...you can combine these into one expectation:

~~~ ruby
expect(alphabet).to start_with("a").and end_with("z")
~~~

You can do the same with `or`. While less common, this is useful
for expressing one of a valid list of values (e.g. when the exact
value is indeterminite):

~~~ ruby
expect(stoplight.color).to eq("red").or eq("green").or eq("yellow")
~~~

I think this could particularly come in handy for expressing invariants
using Jim Weirich's [rspec-given](https://github.com/jimweirich/rspec-given#invariant).

Compound matcher expressions can also be passed as an argument to
another matcher:

~~~ ruby
expect(["food", "drink"]).to include(
  a_string_starting_with("f").and ending_with("d")
)
~~~

Note: in this example, `ending_with` is another alias for the `end_with`
matcher.

## Which matchers support matcher arguments?

In RSpec 3, we've updated many of the matchers to support receiving
matchers as arguments, but not all of them do. In general, we updated
all of the ones where we felt like it made sense. The ones that do not
support matchers are those that have precise matching semantics that
do not allow for a matcher argument.  For example the `eq` matcher is
documented as passing if and only if `actual == expected`. It doesn't
make sense for `eq` to support receiving a matcher argument[^foot_1].

I've compiled a list below of all the built-in matchers that support
receiving matchers as arguments.

### change

The `by` method of the `change` matcher can receive a matcher:

~~~ ruby
k = 0
expect { k += 1.05 }.to change { k }.by( a_value_within(0.1).of(1.0) )
~~~

You can also pass matchers to `from` or `to`:

~~~ ruby
s = "food"
expect { s = "barn" }.to change { s }.
  from( a_string_matching(/foo/) ).
  to( a_string_matching(/bar/) )
~~~

### contain_exactly

`contain_exactly` is a new alias of `match_array`. The semantics are a bit
more clear than `match_array` (now that `match` can match arrays, too, but
`match` requires the ordering to match whereas `match_array` doesn't). It
also allows you to pass the array elements as individual arguments rather
than being forced to pass a single array argument like `match_array` expects.

~~~ ruby
expect(["barn", 2.45]).to contain_exactly(
  a_value_within(0.1).of(2.5),
  a_string_starting_with("bar")
)

# ...which is the same as:

expect(["barn", 2.45]).to match_array([
  a_value_within(0.1).of(2.5),
  a_string_starting_with("bar")
])
~~~

### include

`include` allows you to match against the elements of a collection,
the keys of a hash, or against a subset of the key/value pairs in a hash:

~~~ ruby
expect(["barn", 2.45]).to include( a_string_starting_with("bar") )

expect(12 => "twelve", 3 => "three").to include( a_value_between(10, 15) )

expect(:a => "food", :b => "good").to include(
  :a => a_string_matching(/foo/)
)
~~~

### match

In addition to matching a string against a regex or another string, `match`
now works against arbitrary array/hash data structures, nested as deeply
as you like. Matchers can be used at any level of that nesting:

~~~ ruby
hash = {
  :a => {
    :b => ["foo", 5],
    :c => { :d => 2.05 }
  }
}

expect(hash).to match(
  :a => {
    :b => a_collection_containing_exactly(
      an_instance_of(Fixnum),
      a_string_starting_with("f")
    ),
    :c => { :d => (a_value < 3) }
  }
)
~~~

### raise_error

`raise_error` can accept a matcher for matching against the exception
class or a matcher to match against the message, or both.

~~~ ruby
RSpec::Matchers.define :an_exception_caused_by do |cause|
  match do |exception|
    cause === exception.cause
  end
end

expect {
  begin
    "foo".gsub # requires 2 args
  rescue ArgumentError
    raise "failed to gsub"
  end
}.to raise_error( an_exception_caused_by(ArgumentError) )

expect {
  raise ArgumentError, "missing :foo arg"
}.to raise_error(ArgumentError, a_string_starting_with("missing"))
~~~

### start_with and end_with

These are pretty self-explanatory:

~~~ ruby
expect(["barn", "food", 2.45]).to start_with(
  a_string_matching("bar"),
  a_string_matching("foo")
)

expect(["barn", "food", 2.45]).to end_with(
  a_string_matching("foo"),
  a_value < 3
)
~~~

### throw_symbol

You can pass a matcher to `throw_symbol` to match against the accompanying argument:

~~~ ruby
expect {
  throw :pi, Math::PI
}.to throw_symbol(:pi, a_value_within(0.01).of(3.14))
~~~

### yield_with_args and yield_successive_args

Matchers can be used to specify the yielded arguments for these matchers:

~~~ ruby
expect { |probe|
  "food".tap(&probe)
}.to yield_with_args( a_string_starting_with("f") )

expect { |probe|
  [1, 2, 3].each(&probe)
}.to yield_successive_args( a_value < 2, 2, a_value > 2 )
~~~

## Conclusion

This is one of the new features of RSpec 3 I'm most excited about and I hope
you can see why. This should help make it easier to avoid writing brittle
specs by enabling you to specify _exactly_ what you expect (and nothing
more).

[^foot_1]: You can, of course pass a matcher to `eq`, but it'll treat it just like any other object: it'll compare it to `actual` using `==`, and, if that returns true (i.e. if it's the same object), the expectation will pass.

---

## File: source/blog/2014-02-21-rspec-2-99-and-3-0-beta-2-have-been-released.html.md

---
title: RSpec 2.99 and 3.0 beta2 have been released!
author: Myron Marston
---

The RSpec team has released 3.0.0.beta2 and 2.99.0.beta2.

This is a huge release that includes tons of new features.
I plan to do a full blog post listing and giving examples for
all the notable new 3.0 features at a later date. For now, I've
just got the full release notes.

Thanks to all the contributors who helped make this release happen!

I also want to thank those of you who have put your projects though
the upgrade process and have been using 3.0.0.beta1--your feedback
has been invaluable.

For more details on the upgrade process, see the [beta1
annoucement](/blog/2013/11/rspec-2-99-and-3-0-betas-have-been-released#the_upgrade_process)
blog post.

This will be the last 2.99/3.0 beta release. Next up are the release
candidates!

## Release Notes

### rspec-core 2.99.0.beta2

[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.99.0.beta1...v2.99.0.beta2)

Enhancements:

* Add `is_expected` for one-liners that read well with the
  `expect`-based syntax. `is_expected` is simply defined as
  `expect(subject)` and can be used in an expression like:
  `it { is_expected.to read_well }`. (Myron Marston)
* Backport `skip` from RSpec 3, which acts like `pending` did in RSpec 2
  when not given a block, since the behavior of `pending` is changing in
  RSpec 3. (Xavier Shay)

Deprecations:

* Deprecate inexact `mock_with` config options. RSpec 3 will only support
  the exact symbols `:rspec`, `:mocha`, `:flexmock`, `:rr` or `:nothing`
  (or any module that implements the adapter interface). RSpec 2 did
  fuzzy matching but this will not be supported going forward.
  (Myron Marston)
* Deprecate `show_failures_in_pending_blocks` config option. To achieve
  the same behavior as the option enabled, you can use a custom
  formatter instead. (Xavier Shay)
* Add a deprecation warning for the fact that the behavior of `pending`
  is changing in RSpec 3 -- rather than skipping the example (as it did
  in 2.x when no block was provided), it will run the example and mark
  it as failed if no exception is raised. Use `skip` instead to preserve
  the old behavior. (Xavier Shay)
* Deprecate 's', 'n', 'spec' and 'nested' as aliases for documentation
  formatter. (Jon Rowe)
* Deprecate `RSpec::Core::Reporter#abort` in favor of
  `RSpec::Core::Reporter#finish`. (Jon Rowe)

Bug Fixes:

* Fix failure (undefined method `path`) in end-of-run summary
  when `raise_errors_for_deprecations!` is configured. (Myron Marston)
* Fix issue were overridding spec ordering from the command line wasn't
  fully recognised interally. (Jon Rowe)

### rspec-core 3.0.0.beta2

[Full Changelog](http://github.com/rspec/rspec-core/compare/v3.0.0.beta1...v3.0.0.beta2)

Breaking Changes for 3.0.0:

* Make `mock_with` option more strict. Strings are no longer supported
  (e.g. `mock_with "mocha"`) -- use a symbol instead. Also, unrecognized
  values will now result in an error rather than falling back to the
  null mocking adapter. If you want to use the null mocking adapter,
  use `mock_with :nothing` (as has been documented for a long time).
  (Myron Marston)
* Remove support for overriding RSpec's built-in `:if` and `:unless`
  filters. (Ashish Dixit)
* Custom formatters are now required to call
  `RSpec::Core::Formatters.register(formatter_class, *notifications)`
  where `notifications` is the list of events the formatter wishes to
  be notified about. Notifications are handled by methods matching the
  names on formatters. This allows us to add or remove notifications
  without breaking existing formatters. (Jon Rowe)
* Change arguments passed to formatters. Rather than passing multiple
  arguments (which limits are ability to add additional arguments as
  doing so would break existing formatters), we now pass a notification
  value object that exposes the same data via attributes. This will
  allow us to add new bits of data to a notification event without
  breaking existing formattesr. (Jon Rowe)
* Remove support for deprecated `:alias` option for
  `RSpec.configuration.add_setting`. (Myron Marston)
* Remove support for deprecated `RSpec.configuration.requires = [...]`.
  (Myron Marston)
* Remove support for deprecated `--formatter` CLI option. (Myron Marston)
* Remove support for deprecated `--configure` CLI option. (Myron Marston)
* Remove support for deprecated `RSpec::Core::RakeTask#spec_opts=`.
  (Myron Marston)
* An example group level `pending` block or `:pending` metadata now executes
  the example and cause a failure if it passes, otherwise it will be pending if
  it fails. The old "never run" behaviour is still used for `xexample`, `xit`,
  and `xspecify`, or via a new `skip` method or `:skip` metadata option.
  (Xavier Shay)
* After calling `pending` inside an example, the remainder of the example will
  now be run. If it passes a failure is raised, otherwise the example is marked
  pending. The old "never run" behaviour is provided a by a new `skip` method.
  (Xavier Shay)
* Pending blocks inside an example have been removed as a feature with no
  direct replacement. Use `skip` or `pending` without a block. (Xavier Shay)
* Pending statement is no longer allowed in `before(:all)` hooks. Use `skip`
  instead.  (Xavier Shay)
* Remove `show_failures_in_pending_blocks` configuration option. (Xavier Shay)
* Remove support for specifying the documentation formatter using
  's', 'n', 'spec' or 'nested'. (Jon Rowe)

Enhancements:

* Add example run time to JSON formatter output. (Karthik Kastury)
* Add more suggested settings to the files generated by
  `rspec --init`. (Myron Marston)
* Add `config.alias_example_group_to`, which can be used to define a
  new method that defines an example group with the provided metadata.
  (Michi Huber)
* Add `xdescribe` and `xcontext` as shortcuts to make an example group
  pending. (Myron Marston)
* Add `fdescribe` and `fcontext` as shortcuts to focus an example group.
  (Myron Marston)
* Don't autorun specs via `#at_exit` by default. `require 'rspec/autorun'`
  is only needed when running specs via `ruby`, as it always has been.
  Running specs via `rake` or `rspec` are both unaffected. (Ben Hoskings)
* Add `expose_dsl_globally` config option, defaulting to true. When disabled
  it will remove the monkey patches rspec-core adds to `main` and `Module`
  (e.g. `describe`, `shared_examples_for`, etc).  (Jon Rowe)
* Expose RSpec DSL entry point methods (`describe`,
  `shared_examples_for`, etc) on the `RSpec` constant. Intended for use
  when `expose_dsl_globally` is set to `false`. (Jon Rowe)
* For consistency, expose all example group aliases (including
  `context`) on the `RSpec` constant. If `expose_dsl_globally` is set to
  `true`, also expose them on `main` and `Module`. Historically, only `describe`
  was exposed. (Jon Rowe, Michi Huber)

Bug Fixes:

* Fix failure (undefined method `path`) in end-of-run summary
  when `raise_errors_for_deprecations!` is configured. (Myron Marston)
* Issue error when attempting to use -i or --I on command line,
  too close to -I to be considered short hand for --init. (Jon Rowe)
* Prevent adding formatters to an output target if the same
  formatter has already been added to that output. (Alex Peattie)
* Allow a matcher-generated example description to be used when
  the example is pending. (Myron Marston)
* Ensure the configured `failure_exit_code` is used by the rake
  task when there is a failure. (Jon Rowe)
* Restore behaviour whereby system exclusion filters take priority over working
  directory (was broken in beta1). (Jon Rowe)
* Prevent RSpec mangling file names that have substrings containing `line_number`
  or `default_path`. (Matijs van Zuijlen)

### rspec-expectations 2.99.0.beta2

[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.99.0.beta1...v2.99.0.beta2)

Deprecations:

* Deprecate chaining `by`, `by_at_least`, `by_at_most` or `to` off of
  `expect { }.not_to change { }`. The docs have always said these are
  not supported for the negative form but now they explicitly raise
  errors in RSpec 3. (Myron Marston)
* Change the semantics of `expect { }.not_to change { x }.from(y)`.
  In RSpec 2.x, this expectation would only fail if `x` started with
  the value of `y` and changed. If it started with a different value
  and changed, it would pass. In RSpec 3, it will pass only if the
  value starts at `y` and it does not change. (Myron Marston)
* Deprecate `matcher == value` as an alias for `matcher.matches?(value)`,
  in favor of `matcher === value`. (Myron Marston)
* Deprecate `RSpec::Matchers::OperatorMatcher` in favor of
  `RSpec::Matchers::BuiltIn::OperatorMatcher`. (Myron Marston)
* Deprecate auto-integration with Test::Unit and minitest.
  Instead, include `RSpec::Matchers` in the appropriate test case
  base class yourself. (Myron Marston)
* Deprecate treating `#expected` on a DSL-generated custom matcher
  as an array when only 1 argument is passed to the matcher method.
  In RSpec 3 it will be the single value in order to make diffs
  work properly. (Jon Rowe)

### rspec-expectations 3.0.0.beta2

[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v3.0.0.beta1...v3.0.0.beta2)

Breaking Changes for 3.0.0:

* Remove deprecated support for accessing the `RSpec` constant using
  `Rspec` or `Spec`. (Myron Marston)
* Remove deprecated `RSpec::Expectations.differ=`. (Myron Marston)
* Remove support for deprecated `expect(...).should`. (Myron Marston)
* Explicitly disallow `expect { }.not_to change { }` with `by`,
  `by_at_least`, `by_at_most` or `to`. These have never been supported
  but did not raise explicit errors. (Myron Marston)
* Provide `===` rather than `==` as an alias of `matches?` for
  all matchers.  The semantics of `===` are closer to an RSpec
  matcher than `==`. (Myron Marston)
* Remove deprecated `RSpec::Matchers::OperatorMatcher` constant.
  (Myron Marston)
* Make `RSpec::Expectations::ExpectationNotMetError` subclass
  `Exception` rather than `StandardError` so they can bypass
  a bare `rescue` in end-user code (e.g. when an expectation is
  set from within a rspec-mocks stub implementation). (Myron Marston)
* Remove Test::Unit and Minitest 4.x integration. (Myron Marston)

Enhancements:

* Simplify the failure message of the `be` matcher when matching against:
  `true`, `false` and `nil`. (Sam Phippen)
* Update matcher protocol and custom matcher DSL to better align
  with the newer `expect` syntax. If you want your matchers to
  maintain compatibility with multiple versions of RSpec, you can
  alias the new names to the old. (Myron Marston)
    * `failure_message_for_should` => `failure_message`
    * `failure_message_for_should_not` => `failure_message_when_negated`
    * `match_for_should` => `match`
    * `match_for_should_not` => `match_when_negated`
* Improve generated descriptions from `change` matcher. (Myron Marston)
* Add support for compound matcher expressions using `and` and `or`.
  Simply chain them off of any existing matcher to create an expression
  like `expect(alphabet).to start_with("a").and end_with("z")`.
  (Eloy Espinaco)
* Add `contain_exactly` as a less ambiguous version of `match_array`.
  Note that it expects the expected array to be splatted as
  individual args: `expect(array).to contain_exactly(1, 2)` is
  the same as `expect(array).to match_array([1, 2])`. (Myron Marston)
* Update `contain_exactly`/`match_array` so that it can match against
  other non-array collections (such as a `Set`). (Myron Marston)
* Update built-in matchers so that they can accept matchers as arguments
  to allow you to compose matchers in arbitrary ways. (Myron Marston)
* Add `RSpec::Matchers::Composable` mixin that can be used to make
  a custom matcher composable as well. Note that custom matchers
  defined via `RSpec::Matchers.define` already have this. (Myron
  Marston)
* Define noun-phrase aliases for built-in matchers, which can be
  used when creating composed matcher expressions that read better
  and provide better failure messages. (Myron Marston)
* Add `RSpec::Machers.alias_matcher` so users can define their own
  matcher aliases. The `description` of the matcher will reflect the
  alternate matcher name. (Myron Marston)
* Add explicit `be_between` matcher. `be_between` has worked for a
  long time as a dynamic predicate matcher, but the failure message
  was suboptimal. The new matcher provides a much better failure
  message. (Erik Michaels-Ober)
* Enhance the `be_between` matcher to allow for `inclusive` or `exclusive`
  comparison (e.g. inclusive of min/max or exclusive of min/max).
  (Pedro Gimenez)
* Make failure message for `not_to be #{operator}` less confusing by
  only saying it's confusing when comparison operators are used.
  (Prathamesh Sonpatki)
* Improve failure message of `eq` matcher when `Time` or `DateTime`
  objects are used so that the full sub-second precision is included.
  (Thomas Holmes, Jeff Wallace)
* Add `output` matcher for expecting that a block outputs `to_stdout`
  or `to_stderr`. (Luca Pette, Matthias Günther)
* Forward a provided block on to the `has_xyz?` method call when
  the `have_xyz` matcher is used. (Damian Galarza)
* Provide integration with Minitest 5.x. Require
  `rspec/expectations/minitest_integration` after loading minitest
  to use rspec-expectations with minitest. (Myron Marston)

Bug Fixes:

* Fix wrong matcher descriptions with falsey expected value (yujinakayama)
* Fix `expect { }.not_to change { }.from(x)` so that the matcher only
  passes if the starting value is `x`. (Tyler Rick, Myron Marston)
* Fix hash diffing, so that it colorizes properly and doesn't consider trailing
  commas when performing the diff. (Jared Norman)
* Fix built-in matchers to fail normally rather than raising
  `ArgumentError` when given an object of the wrong type to match
  against, so that they work well in composite matcher expressions like
  `expect([1.51, "foo"]).to include(a_string_matching(/foo/), a_value_within(0.1).of(1.5))`.
  (Myron Marston)

Deprecations:

* Retain support for RSpec 2 matcher protocol (e.g. for matchers
  in 3rd party extension gems like `shoulda`), but it will print
  a deprecation warning. (Myron Marston)

### rspec-mocks 2.99.0.beta2

[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.99.0.beta1...v2.99.0.beta2)

Deprecations:

* Deprecate `RSpec::Mocks::Mock` in favor of `RSpec::Mocks::Double`.
  (Myron Marston)
* Deprecate the `host` argument of `RSpec::Mocks.setup`. Instead
  `RSpec::Mocks::ExampleMethods` should be included directly in the scope where
  RSpec's mocking capabilities are used. (Sam Phippen)
* Deprecate using any of rspec-mocks' features outside the per-test
  lifecycle (e.g. from a `before(:all)` hook). (Myron Marston)
* Deprecate re-using a test double in another example. (Myron Marston)
* Deprecate `and_return { value }` and `and_return` without arguments. (Yuji Nakayama)

### rspec-mocks 3.0.0.beta2

[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v3.0.0.beta1...v3.0.0.beta2)

Breaking Changes for 3.0.0:

* Rename `RSpec::Mocks::Mock` to `RSpec::Mocks::Double`. (Myron Marston)
* Change how to integrate rspec-mocks in other test frameworks. You now
  need to include `RSpec::Mocks::ExampleMethods` in your test context.
  (Myron Marston)
* Prevent RSpec mocks' doubles and partial doubles from being used outside of
  the per-test lifecycle (e.g. from a `before(:all)` hook). (Sam Phippen)
* Remove the `host` argument of `RSpec::Mocks.setup`. Instead
  `RSpec::Mocks::ExampleMethods` should be included directly in the scope where
  RSpec's mocking capabilities are used. (Sam Phippen)
* Make test doubles raise errors if you attempt to use them after they
  get reset, to help surface issues when you accidentally retain
  references to test doubles and attempt to reuse them in another
  example. (Myron Marston)
* Remove support for `and_return { value }` and `and_return` without arguments. (Yuji Nakayama)

Enhancements:

* Add `receive_message_chain` which provides the functionality of the old
  `stub_chain` for the new allow/expect syntax. Use it like so: `allow(...).to
  receive_message_chain(:foo, :bar, :bazz)`. (Sam Phippen).
* Change argument matchers to use `===` as their primary matching
  protocol, since their semantics mirror that of a case or rescue statement
  (which uses `===` for matching). (Myron Marston)
* Add `RSpec::Mocks.with_temporary_scope`, which allows you to create
  temporary rspec-mocks scopes in arbitrary places (such as a
  `before(:all)` hook). (Myron Marston)
* Support keyword arguments when checking arity with verifying doubles.
  (Xavier Shay)

Bug Fixes:

* Fix regression in 3.0.0.beta1 that caused `double("string_name" => :value)`
  to stop working. (Xavier Shay)
* Fix the way rspec-mocks and rspec-core interact so that if users
  define a `let` with the same name as one of the methods
  from `RSpec::Mocks::ArgumentMatchers`, the user's `let` takes
  precedence. (Michi Huber, Myron Marston)
* Fix verified doubles so that their methods match the visibility
  (public, protected or private) of the interface they verify
  against. (Myron Marston)
* Fix verified null object doubles so that they do not wrongly
  report that they respond to anything. They only respond to methods
  available on the interface they verify against. (Myron Marston)
* Fix deprecation warning for use of old `:should` syntax w/o explicit
  config so that it no longer is silenced by an extension gem such
  as rspec-rails when it calls `config.add_stub_and_should_receive_to`.
  (Sam Phippen)
* Fix `expect` syntax so that it does not wrongly emit a "You're
  overriding a previous implementation for this stub" warning when
  you are not actually doing that. (Myron Marston)
* Fix `any_instance.unstub` when used on sub classes for whom the super
  class has had `any_instance.stub` invoked on. (Jon Rowe)
* Fix regression in `stub_chain`/`receive_message_chain` that caused
  it to raise an `ArgumentError` when passing args to the stubbed
  methods. (Sam Phippen)
* Correct stub of undefined parent modules all the way down when stubbing a
  nested constant. (Xavier Shay)
* Raise `VerifyingDoubleNotDefinedError` when a constant is not defined for
  a verifying class double. (Maurício Linhares)
* Remove `Double#to_str`, which caused confusing `raise some_double`
  behavior. (Maurício Linhares)

### rspec-rails 2.99.0.beta2

[Full Changelog](http://github.com/rspec/rspec-rails/compare/v2.99.0.beta1...v2.99.0.beta2)

Deprecations:

* Deprecates the `--webrat` option to the scaffold and request spec generator (Andy Lindeman)
* Deprecates the use of `Capybara::DSL` (e.g., `visit`) in controller specs.
  It is more appropriate to use capybara in feature specs (`spec/features`)
  instead. (Andy Lindeman)

Bug Fixes:

* Use `__send__` rather than `send` to prevent naming collisions (Bradley Schaefer)
* Supports Rails 4.1. (Andy Lindeman)
* Loads ActiveSupport properly to support changes in Rails 4.1. (Andy Lindeman)
* Anonymous controllers inherit from `ActionController::Base` if `ApplicationController`
  is not present. (Jon Rowe)

### rspec-rails 3.0.0.beta2

[Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.0.0.beta1...v3.0.0.beta2)

Breaking Changes for 3.0.0:

* Removes the `--webrat` option for the request spec generator (Andy Lindeman)
* Methods from `Capybara::DSL` (e.g., `visit`) are no longer available in
  controller specs. It is more appropriate to use capybara in feature specs
  (`spec/features`) instead. (Andy Lindeman)
* `infer_base_class_for_anonymous_controllers` is
  enabled by default. (Thomas Holmes)
* Capybara 2.2.0 or above is required for feature specs. (Andy Lindeman)

Enhancements:

* Improve `be_valid` matcher for non-ActiveModel::Errors implementations (Ben Hamill)

Bug Fixes:

* Use `__send__` rather than `send` to prevent naming collisions (Bradley Schaefer)
* Supports Rails 4.1. (Andy Lindeman)
* Routes are drawn correctly for anonymous controllers with abstract
  parents. (Billy Chan)
* Loads ActiveSupport properly to support changes in Rails 4.1. (Andy Lindeman)
* Anonymous controllers inherit from `ActionController::Base` if `ApplicationController`
  is not present. (Jon Rowe)
* Require `rspec/collection_matchers` when `rspec/rails` is required. (Yuji Nakayama)

---

## File: source/blog/2014-05-18-rspec-2-99-and-3-0-rc-1-have-been-released.html.md

---
title: RSpec 2.99 and 3.0 RC1 have been released!
author: Myron Marston
---

The RSpec team has released 3.0.0.rc1 and 2.99.0.rc1! Barring
a new major issue being reported, this will be the last prerelease,
and we'll release 2.99.0 and 3.0.0 final in 2 weeks.

If you're upgrading a project from 2.x, check out the [upgrade
instructions](https://relishapp.com/rspec/docs/upgrade).

If you're curious about what's new in RSpec 3, check back
in a few days -- I'll be posting full list of notable changes
in RSpec 3 soon.

Thanks to all the contributors who helped make this release happen!

## Release Notes

### rspec-core 2.99.0.rc1

[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.99.0.beta2...v2.99.0.rc1)

Enhancements:

* Add `--deprecation-out` CLI option which directs deprecation warnings
  to the named file. (Myron Marston)
* Backport support for `skip` in metadata to skip execution of an example.
  (Xavier Shay, #1472)
* Add `Pathname` support for setting all output streams. (Aaron Kromer)
* Add `test_unit` and `minitest` expectation frameworks. (Aaron Kromer)

Deprecations:

* Deprecate `RSpec::Core::Pending::PendingDeclaredInExample`, use
  `SkipDeclaredInExample` instead. (Xavier Shay)
* Issue a deprecation when `described_class` is accessed from within
  a nested `describe <SomeClass>` example group, since `described_class`
  will return the innermost described class in RSpec 3 rather than the
  outermost described class, as it behaved in RSpec 2. (Myron Marston)
* Deprecate `RSpec::Core::FilterManager::DEFAULT_EXCLUSIONS`,
  `RSpec::Core::FilterManager::STANDALONE_FILTERS` and use of
  `#empty_without_conditional_filters?` on those filters. (Sergey Pchelincev)
* Deprecate `RSpec::Core::Example#options` in favor of
  `RSpec::Core::Example#metadata`. (Myron Marston)
* Issue warning when passing a symbol or hash to `describe` or `context`
  as the first argument. In RSpec 2.x this would be treated as metadata
  but in RSpec 3 it'll be treated as the described object. To continue
  having it treated as metadata, pass a description before the symbol or
  hash. (Myron Marston)
* Deprecate `RSpec::Core::BaseTextFormatter::VT100_COLORS` and
  `RSpec::Core::BaseTextFormatter::VT100_COLOR_CODES` in favour
  of `RSpec::Core::BaseTextFormatter::ConsoleCodes::VT100_CODES` and
  `RSpec::Core::BaseTextFormatter::ConsoleCodes::VT100_CODE_VALUES`.
  (Jon Rowe)
* Deprecate `RSpec::Core::ExampleGroup.display_name` in favor of
  `RSpec::Core::ExampleGroup.description`. (Myron Marston)
* Deprecate `RSpec::Core::ExampleGroup.describes` in favor of
  `RSpec::Core::ExampleGroup.described_class`. (Myron Marston)
* Deprecate `RSpec::Core::ExampleGroup.alias_example_to` in favor of
  `RSpec::Core::Configuration#alias_example_to`. (Myron Marston)
* Deprecate `RSpec::Core::ExampleGroup.alias_it_behaves_like_to` in favor
  of `RSpec::Core::Configuration#alias_it_behaves_like_to`. (Myron Marston)
* Deprecate `RSpec::Core::ExampleGroup.focused` in favor of
  `RSpec::Core::ExampleGroup.focus`. (Myron Marston)
* Add deprecation warning for `config.filter_run :focused` since
  example aliases `fit` and `focus` will no longer include
  `:focused` metadata but will continue to include `:focus`. (Myron Marston)
* Deprecate filtering by `:line_number` (e.g. `--line-number` from the
  CLI). Use location filtering instead. (Myron Marston)
* Deprecate `--default_path` as an alternative to `--default-path`. (Jon Rowe)
* Deprecate `RSpec::Core::Configuration#warnings` in favor of
  `RSpec::Core::Configuration#warnings?`. (Myron Marston)
* Deprecate `share_examples_for` in favor of `shared_examples_for` or
  just `shared_examples`. (Myron Marston)
* Deprecate `RSpec::Core::CommandLine` in favor of
  `RSpec::Core::Runner`. (Myron Marston)
* Deprecate `#color_enabled`, `#color_enabled=` and `#color?` in favour of
  `#color`, `#color=` and `#color_enabled? output`. (Jon Rowe)
* Deprecate `#filename_pattern` in favour of `#pattern`. (Jon Rowe)
* Deprecate `#backtrace_cleaner` in favour of `#backtrace_formatter`. (Jon Rowe)
* Deprecate mutating `RSpec::Configuration#formatters`. (Jon Rowe)
* Deprecate `stdlib` as an available expectation framework in favour of
  `test_unit` and `minitest`. (Aaron Kromer)

Bug Fixes:

* Issue a warning when you set `config.deprecation_stream` too late for
  it to take effect because the reporter has already been setup. (Myron Marston)
* `skip` with a block should not execute the block. (Xavier Shay)

### rspec-core 3.0.0.rc1

[Full Changelog](http://github.com/rspec/rspec-core/compare/v3.0.0.beta2...v3.0.0.rc1)

Breaking Changes for 3.0.0:

* Change `described_class` so that in a nested group like `describe
  MyClass`, it returns `MyClass` rather than the outer group's described
  class. (Myron Marston)
* Refactor filter manager so that it no longer subclasses Hash and has a
  tighter, more domain-specific interface. (Sergey Pchelincev)
* Remove legacy colours definitions from `BaseTextFormatter`. (Jon Rowe)
* Remove console color definitions from `BaseTextFormatter`. (Jon Rowe)
* Restructure example group metadata so that the computed keys are
  exposed directly off of the metadata hash rather than being on
  a nested `:example_group` subhash. In addition, the parent example
  group metadata is now available as `[:parent_example_group]` rather
  than `[:example_group][:example_group]`. Deprecated access via the
  old key structure is still provided. (Myron Marston)
* Remove `:describes` metadata key. It duplicates `:described_class`
  for no good reason. Deprecated access via `:describes` is still
  provided. (Myron Marston)
* Rename `:example_group_block` metadata key to `:block`.
  (Myron Marston)
* Remove deprecated `RSpec::Core::Example#options`. (Myron Marston)
* Move `BaseTextFormatter#colorize_summary` to `SummaryNotification#colorize_with`
  (Jon Rowe).
* `describe some_hash` treated `some_hash` as metadata in RSpec 2.x but
  will treat it as the described object in RSpec 3.0. Metadata must
  always come after the description args. (Myron Marston)
* Remove deprecated `display_name` alias of `ExampleGroup.description`.
  (Myron Marston)
* Remove deprecated `describes` alias of `ExampleGroup.described_class`.
  (Myron Marston)
* Remove deprecated `RSpec::Core::ExampleGroup.alias_it_behaves_like_to`.
  Use `RSpec::Core::Configuration#alias_it_behaves_like_to` instead.
  (Myron Marston)
* Remove deprecated `RSpec::Core::ExampleGroup.alias_example_to`.
  Use `RSpec::Core::Configuration#alias_example_to` instead.
  (Myron Marston)
* Removed `focused` example alias and change example/group aliases
  `fit`, `focus`, `fcontext` and `fdescribe` to no longer include
  `:focused => true` metadata. They only contain `:focus => true`
  metadata now. This means that you will need to filter them with
  `filter_run :focus`, not `filter_run :focused`. (Myron Marston)
* Remove `--line-number` filtering. It's semantically dubious since it's
  a global filter (potentially applied to multiple files) but there's no
  meaningful connection between the same line number in multiple files.
  Instead use the `rspec path/to/spec.rb:23:46` form, which is terser
  and makes more sense as it is scoped to a file. (Myron Marston)
* Remove `--default_path` as an alias for `--default-path`. (Jon Rowe)
* Remove deprecated `share_examples_for`. There's still
  `shared_examples` and `shared_examples_for`. (Myron Marston)
* Rename `RSpec::Core::Configuration#warnings` to
  `RSpec::Core::Configuration#warnings?` since it's a boolean flag.
  (Myron Marston)
* RSpec's global state is no longer reset after a spec run. This gives
  more flexibility to alternate runners to decide when and if they
  want the state reset. Alternate runners are now responsible for
  calling this (or doing a similar reset) if they are going to run
  the spec suite multiple times in the same process. (Sam Phippen)
* Merge `RSpec::Core::CommandLine` (never formally declared public)
  into `RSpec::Core::Runner`. (Myron Marston)
* Remove `color_enabled` as an alias of `color`. (Jon Rowe)
* Remove `backtrace_cleaner` as an alias of `backtrace_formatter`. (Jon Rowe)
* Remove `filename_pattern` as an alias of `pattern`. (Jon Rowe)
* Extract support for legacy formatters to `rspec-legacy_formatters`. (Jon Rowe)
* `RSpec::Configuration#formatters` now returns a dup to prevent mutation. (Jon Rowe)
* Replace `stdlib` as an available expectation framework with `test_unit` and
  `minitest`. (Aaron Kromer)
* Remove backtrace formatting helpers from `BaseTextFormatter`. (Jon Rowe)
* Extract profiler support to `ProfileFormatter` and `ProfileNotification`.
  Formatters should implement `dump_profile` if they wish to respond to `--profile`.
  (Jon Rowe)
* Extract remaining formatter state to reporter and notifications. Introduce
  `ExamplesNotification` to share information about examples that was previously
  held in `BaseFormatter`. (Jon Rowe)

Enhancements:

* Add `config.default_formatter` attribute, which can be used to set a
  formatter which will only be used if no other formatter is set
  (e.g. via `--formatter`). (Myron Marston)
* Support legacy colour definitions in `LegacyFormatterAdaptor`. (Jon Rowe)
* Migrate `execution_result` (exposed by metadata) from a hash to a
  first-class object with appropriate attributes. `status` is now
  stored and returned as a symbol rather than a string. It retains
  deprecated hash behavior for backwards compatibility. (Myron Marston)
* Provide console code helper for formatters. (Jon Rowe)
* Use raw ruby hashes for the metadata hashes rather than a subclass of
  a hash. Computed metadata entries are now computed in advance rather
  than being done lazily on first access. (Myron Marston)
* Add `:block` metadata entry to the example metadata, bringing
  parity with `:block` in the example group metadata. (Myron Marston)
* Add `fspecify` and `fexample` as aliases of `specify` and `example`
  with `:focus => true` metadata for parity with `fit`. (Myron Marston)
* Add legacy support for `colorize_summary`. (Jon Rowe)
* Restructure runner so it can be more easily customized in a subclass
  for an alternate runner. (Ben Hoskings)
* Document `RSpec::Core::ConfigurationOptions` as an officially
  supported public API. (Myron Marston)
* Add `--deprecation-out` CLI option which directs deprecation warnings
  to the named file. (Myron Marston)
* Minitest 5 compatability for `expect_with :stdlib` (now available as
  `expect_with :minitest`). (Xavier Shay)
* Reporter now notifies formatters of the load time of RSpec and your
  specs via `StartNotification` and `SummaryNotification`. (Jon Rowe)
* Add `disable_monkey_patching!` config option that disables all monkey
  patching from whatever pieces of RSpec you use. (Alexey Fedorov)
* Add `Pathname` support for setting all output streams. (Aaron Kromer)
* Add `config.define_derived_metadata`, which can be used to apply
  additional metadata to all groups or examples that match a given
  filter. (Myron Marston)
* Provide formatted and colorized backtraces via `FailedExampleNotification`
  and send `PendingExampleFixedNotifications` when the error is due to a
  passing spec you expect to fail. (Jon Rowe)
* Add `dump_profile` to formatter API to allow formatters to implement
  support for `--profile`. (Jon Rowe)
* Allow colourising text via `ConsoleCodes` with RSpec 'states'
  (e.g. `:success`, `:failure`) rather than direct colour codes. (Jon Rowe)
* Expose `fully_formatted` methods off the formatter notification objects
  that make it easy for a custom formatter to produce formatted output
  like rspec-core's. (Myron Marston)

Bug Fixes:

* Fix `spec_helper.rb` file generated by `rspec --init` so that the
  recommended settings correctly use the documentation formatter
  when running one file. (Myron Marston)
* Fix ordering problem where descriptions were generated after
  tearing down mocks, which resulted in unexpected exceptions.
  (Bradley Schaefer, Aaron Kromer, Andrey Savchenko)
* Allow a symbol to be used as an implicit subject (e.g. `describe :foo`).
  (Myron Marston)
* Prevent creating an isolated context (i.e. using `RSpec.describe`) when
  already inside a context. There is no reason to do this, and it could
  potentially cause unexpected bugs. (Xavier Shay)
* Fix shared example group scoping so that when two shared example
  groups share the same name at different levels of nested contexts,
  the one in the nearest context is used. (Myron Marston)
* Fix `--warnings` option so that it enables warnings immediately so
  that it applies to files loaded by `--require`. (Myron Marston)
* Issue a warning when you set `config.deprecation_stream` too late for
  it to take effect because the reporter has already been setup. (Myron Marston)
* Add the full `RSpec::Core::Example` interface to the argument yielded
  to `around` hooks. (Myron Marston)
* Line number always takes precendence when running specs with filters.
  (Xavier Shay)
* Ensure :if and :unless metadata filters are treated as a special case
  and are always in-effect. (Bradley Schaefer)
* Ensure the currently running installation of RSpec is used when
  the rake task shells out to `rspec`, even if a newer version is also
  installed. (Postmodern)
* Using a legacy formatter as default no longer causes an infinite loop.
  (Xavier Shay)

### rspec-expectations 2.99.0.rc1

[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.99.0.beta2...2.99.0.rc1)

Deprecations:

* Deprecate `matcher_execution_context` attribute on DSL-defined
  custom matchers. (Myron Marston)
* Deprecate `RSpec::Matchers::Pretty#_pretty_print`. (Myron Marston)
* Deprecate `RSpec::Matchers::Pretty#expected_to_sentence`. (Myron Marston)
* Deprecate `RSpec::Matchers::Configuration` in favor of
  `RSpec::Expectations::Configuration`. (Myron Marston)
* Deprecate `be_xyz` predicate matcher on an object that doesn't respond to
  `xyz?` or `xyzs?`. (Daniel Fone)
* Deprecate `have_xyz` matcher on an object that doesn't respond to `has_xyz?`.
  (Daniel Fone)
* Deprecate `have_xyz` matcher on an object that has a private method `has_xyz?`.
  (Jon Rowe)
* Issue a deprecation warning when a block expectation expression is
  used with a matcher that doesn't explicitly support block expectations
  via `supports_block_expectations?`. (Myron Marston)
* Deprecate `require 'rspec-expectations'`. Use
  `require 'rspec/expectations'` instead. (Myron Marston)

### rspec-expectations 3.0.0.rc1

[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v3.0.0.beta2...v3.0.0.rc1)

Breaking Changes for 3.0.0:

* Remove `matcher_execution_context` attribute from DSL-defined
  custom matchers. (Myron Marston)
* Remove `RSpec::Matchers::Pretty#_pretty_print`. (Myron Marston)
* Remove `RSpec::Matchers::Pretty#expected_to_sentence`. (Myron Marston)
* Rename `RSpec::Matchers::Configuration` constant to
  `RSpec::Expectations::Configuration`. (Myron Marston)
* Prevent `have_xyz` predicate matchers using private methods.
  (Adrian Gonzalez)
* Block matchers must now implement `supports_block_expectations?`.
  (Myron Marston)
* Stop supporting `require 'rspec-expectations'`.
  Use `require 'rspec/expectations'` instead. (Myron Marston)

Bug Fixes:

* Fix `NoMethodError` triggered by beta2 when `YARD` was loaded in
  the test environment. (Myron Marston)
* Fix `be_xyz` matcher to accept a `do...end` block. (Myron Marston)
* Fix composable matcher failure message generation logic
  so that it does not blow up when given `$stdout` or `$stderr`.
  (Myron Marston)
* Fix `change` matcher to work properly with `IO` objects.
  (Myron Marston)
* Fix `exist` matcher so that it can be used in composed matcher
  expressions involving objects that do not implement `exist?` or
  `exists?`. (Daniel Fone)
* Fix composable matcher match logic so that it clones matchers
  before using them in order to work properly with matchers
  that use internal memoization based on a given `actual` value.
  (Myron Marston)
* Fix `be_xyz` and `has_xyz` predicate matchers so that they can
  be used in composed matcher expressions involving objects that
  do not implement the predicate method. (Daniel Fone)

Enhancements:

* Document the remaining public APIs. rspec-expectations now has 100% of
  the public API documented and will remain that way (as new undocumented
  methods will fail the build). (Myron Marston)
* Improve the formatting of BigDecimal objects in `eq` matcher failure
  messages. (Daniel Fone)
* Improve the failure message for `be_xyz` predicate matchers so
  that it includes the `inspect` output of the receiver.
  (Erik Michaels-Ober, Sam Phippen)
* Add `all` matcher, to allow you to specify that a given matcher
  matches all elements in a collection:
  `expect([1, 3, 5]).to all( be_odd )`. (Adam Farhi)
* Add boolean aliases (`&`/`|`) for compound operators (`and`/`or`). (Adam Farhi)
* Give users a clear error when they wrongly use a value matcher
  in a block expectation expression (e.g. `expect { 3 }.to eq(3)`)
  or vice versa.  (Myron Marston)

### rspec-mocks 2.99.0.rc1

[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.99.0.beta2...v2.99.0.rc1)

Deprecations:

* Deprecate `RSpec::Mocks::TestDouble.extend_onto`. (Myron Marston)
* Deprecate `RSpec::Mocks::ConstantStubber`. (Jon Rowe)
* Deprecate `Marshal.dump` monkey-patch without opt-in. (Xavier Shay)

### rspec-mocks 3.0.0.rc1

[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v3.0.0.beta2...v3.0.0.rc1)

Breaking Changes for 3.0.0:

* Remove `RSpec::Mocks::TestDouble.extend_onto`. (Myron Marston)
* Remove `RSpec::Mocks::ConstantStubber`. (Jon Rowe)
* Make monkey-patch of Marshal to support dumping of stubbed objects opt-in.
  (Xavier Shay)

Enhancements:

* Instead of crashing when cleaning up stub methods on a frozen object, it now
  issues a warning explaining that it's impossible to clean up the stubs.
  (Justin Coyne and Sam Phippen)
* Add meaningful descriptions to `anything`, `duck_type` and `instance_of` argument
  matchers. (Jon Rowe)

Bug Fixes:

* Fix regression introduced in 3.0.0.beta2 that caused
  `double.as_null_object.to_str` to return the double rather
  than a string. (Myron Marston)
* Fix bug in `expect(dbl).to receive_message_chain(:foo, :bar)` where it was
  not setting an expectation for the last message in the chain.
  (Jonathan del Strother)
* Allow verifying partial doubles to have private methods stubbed. (Xavier Shay)
* Fix bug with allowing/expecting messages on Class objects which have had
  their singleton class prepended to. (Jon Rowe)
* Fix an issue with 1.8.7 not running implementation blocks on partial doubles.
  (Maurício Linhares)
* Prevent `StackLevelTooDeep` errors when stubbing an `any_instance` method that's
  accessed in `inspect` by providing our own inspect output. (Jon Rowe)
* Fix bug in `any_instance` logic that did not allow you to mock or stub
  private methods if `verify_partial_doubles` was configured. (Oren Dobzinski)
* Include useful error message when trying to observe an unimplemented method
  on an any instance. (Xavier Shay)
* Fix `and_call_original` to work properly when multiple classes in an
  inheritance hierarchy have been stubbed with the same method. (Myron Marston)
* Fix `any_instance` so that it updates existing instances that have
  already been stubbed. (Myron Marston)
* Fix verified doubles so that their class name is included in failure
  messages. (Myron Marston)
* Fix `expect_any_instance_of` so that when the message is received
  on an individual instance that has been directly stubbed, it still
  satisfies the expectation. (Sam Phippen, Myron Marston)
* Explicitly disallow using `any_instance` to mock or stub a method
  that is defined on a module prepended onto the class. This triggered
  `SystemStackError` before and is very hard to support so we are not
  supporting it at this time. (Myron Marston)

### rspec-rails 2.99.0.rc1

[Full Changelog](http://github.com/rspec/rspec-rails/compare/v2.99.0.beta2...v2.99.0.rc1)

Deprecations

* Deprecates `stub_model` and `mock_model` in favor of the
  `rspec-activemodel-mocks` gem. (Thomas Holmes)
* Issue a deprecation to instruct users to configure
  `config.infer_spec_type_from_file_location!` during the
  upgrade process since spec type inference is opt-in in 3.0.
  (Jon Rowe)
* Issue a deprecation when `described_class` is accessed in a controller
  example group that has used the `controller { }` macro to generate an
  anonymous controller class, since in 2.x, `described_class` would
  return that generated class but in 3.0 it will continue returning the
  class passed to `describe`. (Myron Marston)

### rspec-rails 3.0.0.rc1

[Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.0.0.beta2...v3.0.0.rc1)

Breaking Changes for 3.0.0:

* Extracts the `mock_model` and `stub_model` methods to the
  `rspec-activemodel-mocks` gem. (Thomas Holmes)
* Spec types are no longer inferred by location, they instead need to be
  explicitly tagged. The old behaviour is enabled by
  `config.infer_spec_type_from_file_location!`, which is still supplied
  in the default generated `spec_helper.rb`. (Xavier Shay, Myron Marston)
* `controller` macro in controller specs no longer mutates
  `:described_class` metadata. It still overrides the subject and sets
  the controller, though. (Myron Marston)
* Stop depending on or requiring `rspec-collection_matchers`. Users who
  want those matchers should add the gem to their Gemfile and require it
  themselves. (Myron Marston)
* Removes runtime dependency on `ActiveModel`. (Rodrigo Rosenfeld Rosas)

Enhancements:

* Supports Rails 4.x reference attribute ids in generated scaffold for view
  specs. (Giovanni Cappellotto)
* Add `have_http_status` matcher. (Aaron Kromer)
* Add spec type metadata to generator templates. (Aaron Kromer)

Bug Fixes:

* Fix an inconsistency in the generated scaffold specs for a controller. (Andy Waite)
* Ensure `config.before(:all, :type => <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)

---

## File: source/blog/2014-05-21-notable-changes-in-rspec-3.html.md

---
title: Notable Changes in RSpec 3
author: Myron Marston
---

Update: there's a [Japanese
translation](http://nilp.hatenablog.com/entry/2014/05/28/003335) of this
available now.

RSpec 3.0.0 RC1 was [released a couple days
ago](/blog/2014/05/rspec-2-99-and-3-0-rc-1-have-been-released),
and 3.0.0 final is just around the corner.  We've been using the betas for the
last 6 months and we're excited to share them with you. Here's whats new:

## Across all gems

### Removed support for Ruby 1.8.6 and 1.9.1

These versions of Ruby were end-of-lifed long ago and
RSpec 3 does not support them.

### Improved Ruby 2.x support

Recent releases of RSpec 2.x (i.e. those that came out after
Ruby 2.0 was released) have officially supported Ruby 2, but RSpec 3's
support is greatly improved. We now provide support for working
with the new features of Ruby 2, like keyword arguments and prepended
modules.

### New rspec-support gem

[rspec-support](https://github.com/rspec/rspec-support) is a new gem
that we're using for common code needed by more than one of
rspec-(core|expectations|mocks|rails). It doesn't currently contain
any public APIs intended for use by end users or extension library
authors, but we may make some of its APIs public in the future.

If you run bleeding-edge RSpec by sourcing it from github in your
Gemfile, you'll need to start doing the same for rspec-support as well.

### Robust, well-tested upgrade process

Every breaking change in RSpec 3 has a corresponding deprecation warning in 2.99.
Throughout the betas we have done many upgrades to ensure this process is as
smooth as possible. We've put together [step by step upgrade
instructions](https://relishapp.com/rspec/docs/upgrade).

The upgrade process also highlights RSpec's new deprecation system
which is highly configurable (allowing you to output deprecations
into a file or turn all deprecations into errors) and is designed
to minimize duplicated deprecation output.

### Improved Docs

We've put a ton of effort into updating the API docs for all gems.
They're currently hosted on [rubydoc.info](http://rubydoc.info/):

* [rspec-core](http://rubydoc.info/github/rspec/rspec-core/frames)
* [rspec-expectations](http://rubydoc.info/github/rspec/rspec-expectations/frames)
* [rspec-mocks](http://rubydoc.info/github/rspec/rspec-mocks/frames)
* [rspec-rails](http://rubydoc.info/github/rspec/rspec-rails/frames)

...but we're currently working on updating [rspec.info](http://rspec.info/)
to self-host them.

While the docs are still a work-in-progress (and frankly, always will be),
we've made sure to explicitly declare all public APIs as part of
[SemVer](http://semver.org/) compliance. We're absolutely committed to
maintaining all public APIs through all 3.x releases. Private APIs, on
the other hand, are labeled as such because we specifically want to
reserve the flexibility to change them willy nilly in any 3.x release.

Please do not use APIs we've declared private. If you find yourself
with a need not addressed by the existing public APIs, please ask.
We'll gladly either make a private API public for your needs
or add a new API to meet your use case.

### Gems are now signed

We've started signing our gem releases. While the current gem signing
system is far from ideal, and [a better
solution](http://corner.squareup.com/2013/12/securing-rubygems-with-tuf-part-1.html)
is being developed, it's better than nothing. We've put our public cert on
[GitHub](https://github.com/rspec/rspec/blob/master/certs/rspec.pem).

For more details on the current gem signing system, see [A Practical
Guide to Using Signed Ruby
Gems](http://blog.meldium.com/home/2013/3/3/signed-rubygems-part).

### Zero monkey patching mode

RSpec can now be used without any monkey patching whatsoever.
Much of the groundwork for this was laid in recent 2.x releases
that added the new `expect`-based syntax to rspec-expectations
and rspec-mocks. We've gone the rest of the way in RSpec 3 and
provided alternatives for the remaining monkey patches.

For convenience you can disable all of the monkey patches with one option:

~~~ ruby
# spec/spec_helper.rb
RSpec.configure do |c|
  c.disable_monkey_patching!
end
~~~

Thanks to [Alexey Fedorov](https://github.com/waterlink) for
[implementing](https://github.com/rspec/rspec-core/pull/1465) this config option.

For more info:

* [Documentation](http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/Configuration#disable_monkey_patching%21-instance_method)

## rspec-core

### New names for hook scopes: `:example` and `:context`

RSpec 2.x had three different hook scopes:

~~~ ruby
describe MyClass do
  before(:each) { } # runs before each example in this group
  before(:all)  { } # runs once before the first example in this group
end
~~~

~~~ ruby
# spec/spec_helper.rb
RSpec.configure do |c|
  c.before(:each)  { } # runs before each example in the entire test suite
  c.before(:all)   { } # runs before the first example of each top-level group
  c.before(:suite) { } # runs once after all spec files have been loaded, before the first spec runs
end
~~~

At times, users have expressed confusion around what `:each` vs `:all`
means, and `:all` in particular can be confusing when you use it in a
config block:

~~~ ruby
# spec/spec_helper.rb
RSpec.configure do |c|
  c.before(:all) { }
end
~~~

In this context, the term `:all` suggests that this hook will run once
before all examples in the suite — but that is what `:suite` is for.

In RSpec 3, `:each` and `:all` have aliases that make their scope
more explicit: `:example` is an alias of `:each` and `:context`
is an alias of `:all`. Note that `:each` and `:all` are _not_ deprecated
and we have no plans to do so.

Thanks to [John Feminella](https://github.com/fj) for
[implementing](https://github.com/rspec/rspec-core/pull/1174) this.

For more info:

* [Documentation](http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/Hooks#before-instance_method)
* [rspec-core #297 - original discussion](https://github.com/rspec/rspec-core/pull/297)

### DSL methods yield the example as an argument

`RSpec::Core::Example` provides access to all the details about an
example: its description, location, metadata, execution result, etc.
In RSpec 2.x the example was exposed via an `example` method that could
be accessed from any hook or individual example:

~~~ ruby
describe MyClass do
  before(:each) { puts example.metadata }
end
~~~

In RSpec 3, we've removed the `example` method. Instead, the example
instance is yielded to all example-scoped DSL methods as an explicit
argument:

~~~ ruby
describe MyClass do
  before(:example) { |ex| puts ex.metadata }
  let(:example_description) { |ex| ex.description }

  it 'accesses the example' do |ex|
    # use ex
  end
end
~~~

Thanks to [David Chelimsky](https://github.com/dchelimsky) for coming up
with the idea and
[implementing](https://github.com/rspec/rspec-core/pull/666) it!

For more info:

* [Documentation](http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/Example)

### New `expose_dsl_globally` config option to disable rspec-core monkey patching

RSpec 2.x monkey patched `main` and `Module` to provide top level
methods like `describe`, `shared_examples_for` and `shared_context`:

~~~ ruby
shared_examples_for "something" do
end

module MyGem
  describe SomeClass do
    it_behaves_like "something"
  end
end
~~~

In RSpec 3, these methods are now also available on the `RSpec` module
(in addition to still being available as monkey patches):

~~~ ruby
RSpec.shared_examples_for "something" do
end

module MyGem
  RSpec.describe SomeClass do
    it_behaves_like "something"
  end
end
~~~

You can completely remove rspec-core's monkey patching (which
would make the first example above raise `NoMethodError`) by
setting the new `expose_dsl_globally` config option to `false`:

~~~ ruby
# spec/spec_helper.rb
RSpec.configure do |config|
  config.expose_dsl_globally = false
end
~~~

Thanks to [Jon Rowe](https://github.com/JonRowe) for
[implementing](https://github.com/rspec/rspec-core/pull/1036) this.

For more info:

* [Documentation](https://relishapp.com/rspec/rspec-core/v/3-0/docs/configuration/global-namespace-dsl)

### Define example group aliases with `alias_example_group_to`

In RSpec 2.x, we provided an API that allowed you to define `example`
aliases with attached metadata. For example, this is used internally to
define `fit` as an alias for `it` with `:focus => true` metadata:

~~~ ruby
# spec/spec_helper.rb
RSpec.configure do |config|
  config.alias_example_to :fit, :focus => true
end
~~~

In RSpec 3, we've extended this feature to example groups:

~~~ ruby
# spec/spec_helper.rb
RSpec.configure do |config|
  config.alias_example_group_to :describe_model, :type => :model
end
~~~

You could use this example in a project using rspec-rails and use
`describe_model User` rather than `describe User, :type => :model`.

Thanks to [Michi Huber](https://github.com/michihuber) for
[implementing](https://github.com/rspec/rspec-core/pull/1236) this.

For more info:

* [Documentation](http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/Configuration#alias_example_group_to-instance_method)
* [rspec-core #493 - original discussion](https://github.com/rspec/rspec-core/issues/493)

### New example group aliases: `xdescribe`, `xcontext`, `fdescribe`, `fcontext`

Besides including an API to define example group aliases, we've also
included several additional built-in aliases (on top of `describe` and
`context`):

* `xdescribe`/`xcontext`, like `xit` for examples, can be used to temporarily skip an
  example group.
* `fdescribe`/`fcontext`, like `fit` for examples, can be used to temporarily add
  `:focus => true` metadata to an example group so that you can easily
  filter to the focused examples and groups via `config.filter_run :focus`.

For more info:

* [Documentation](http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/ExampleGroup)
* [rspec-core #1255 - implementation](https://github.com/rspec/rspec-core/pull/1255)

### Changes to `pending` semantics (and introduction of `skip`)

Pending examples are now run to check if they are actually passing. If
a pending block fails, then it will be marked pending as before. However, if
it succeeds it will cause a failure. This helps ensure that pending examples are
valid, and also that they are promptly dealt with when the behaviour they
describe is implemented.

To support the old "never run" behaviour, the `skip` method and metadata has
been added. None of the following examples will ever be run:

~~~ ruby
describe Post do
  skip 'not implemented yet' do
  end

  it 'does something', :skip => true do
  end

  it 'does something', :skip => 'reason explanation' do
  end

  it 'does something else' do
    skip
  end

  it 'does something else' do
    skip 'reason explanation'
  end
end
~~~

With this change, passing a block to `pending` within an example no longer
makes sense, so that behaviour has been removed.

Thanks to [Xavier Shay](http://xaviershay.com) for
[implementing](https://github.com/rspec/rspec-core/pull/1267) this.

For more info:

* [Documentation](https://relishapp.com/rspec/rspec-core/v/3-0/docs/pending-and-skipped-examples)
* [rspec-core #1208 - original discussion](https://github.com/rspec/rspec-core/issues/1208)

### New API for one-liners: `is_expected`

RSpec has had a one-liner syntax for many years:

~~~ ruby
describe Post do
  it { should allow_mass_assignment_of(:title) }
end
~~~

In this context, `should` is _not_ the monkey-patched `should`
that can be removed by configuring rspec-expectations to only
support the `:expect` syntax. It doesn't have the baggage that
monkey-patching `Object` with `should` brings, and is always
available regardless of your syntax configuration.

Some users have expressed confusion about how this `should` relates
to the `expect` syntax and if you can continue using it. It will continue
to be available in RSpec 3 (again, regardless of your syntax configuration),
but we've also added an alternate API that is a bit more consistent with
the `expect` syntax:

~~~ ruby
describe Post do
  it { is_expected.to allow_mass_assignment_of(:title) }
end
~~~

`is_expected` is defined very simply as `expect(subject)` and also
supports negative expectations via `is_expected.not_to matcher`.

For more info:

* [Documentation](http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/MemoizedHelpers#is_expected-instance_method)
* [rspec-core #1180 - implementation](https://github.com/rspec/rspec-core/pull/1180)

### Example groups can be ordered individually

RSpec 2.8 introduced random ordering to RSpec, which is very useful for
surfacing unintentional ordering dependencies in your spec suite. In
RSpec 3, it's no longer an all-or-nothing feature. You can control how
individual example groups are ordered by tagging them with appropriate
metadata:

~~~ ruby
describe MyClass, :order => :defined do
  # examples in this group will always run in defined order,
  # regardless of any other ordering configuration.
end

describe MyClass, :order => :random do
  # examples in this group will always run in random order,
  # regardless of any other ordering configuration.
end
~~~

This is particularly useful for migrating from defined to random
ordering, as it allows you to deal with ordering dependencies one-by-one
as you opt-in to the feature for particular groups rather than
having to solve the issues all at once.

As part of this we've also renamed `--order default` to `--order
defined`, because we realized that "default" was a highly overloaded
term.

Thanks to [Andy Lindeman](https://github.com/alindeman) and [Sam
Phippen](https://github.com/samphippen) for helping
[implement](https://github.com/rspec/rspec-core/pull/1025) this feature.

For more info:

* [Documentation](http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/Configuration#register_ordering-instance_method)

### New ordering strategy API

In RSpec 3, we've overhauled the ordering strategy API. What used to be
[three](http://rubydoc.info/gems/rspec-core/2.14.8/RSpec/Core/Configuration:order_examples)
[different](http://rubydoc.info/gems/rspec-core/2.14.8/RSpec/Core/Configuration:order_groups)
[methods](http://rubydoc.info/gems/rspec-core/2.14.8/RSpec/Core/Configuration:order_groups_and_examples)
is now one method: `register_ordering`. Use it to define a named ordering
strategy:

~~~ ruby
# spec/spec_helper.rb
RSpec.configure do |config|
  config.register_ordering(:description_length) do |list|
    list.sort_by { |item| item.description.length }
  end
end
~~~

~~~ ruby
describe MyClass, :order => :description_length do
  # ...
end
~~~

Or, you can use it to define the global ordering:

~~~ ruby
# spec/spec_helper.rb
RSpec.configure do |config|
  config.register_ordering(:global) do |list|
    # sort them alphabetically
    list.sort_by { |item| item.description }
  end
end
~~~

The `:global` ordering is used to order the top-level example groups
and to order all example groups that do not have `:order` metadata.

For more info:

* [Documentation](http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/Configuration#register_ordering-instance_method)
* [rspec-core #1025 - implementation](https://github.com/rspec/rspec-core/pull/1025)

### `rspec --init` improvements

The `rspec` command has provided the `--init` option to setup a project
skeleton for a long time. In RSpec 3, the files it produces have been
greatly improved to provide a better out-of-the-box experience and
to provide a `spec/spec_helper.rb` file with more recommended settings.

Note that recommended settings which are not slated to become future
defaults are commented out in the generated file, so it's a good idea
to open the file and accept the recommendations you want.

For more info:

* [rspec-core #1219 - implementation](https://github.com/rspec/rspec-core/pull/1219)

### New `--dry-run` CLI option

This option will print the formatter output of your spec suite
without running any of the examples or hooks. It's particularly
useful as way to review your suite's documentation output without
waiting for your specs to run or worrying about their pass/fail
status.

Thanks to [Thomas Stratmann](https://github.com/schnittchen) for
[contributing](https://github.com/rspec/rspec-core/pull/1028) this!

For more info:

* [Documentation](https://relishapp.com/rspec/rspec-core/v/3-0/docs/command-line/dry-run-option)
* [rspec-core #1022 - original discussion](https://github.com/rspec/rspec-core/issues/1022)

### Formatter API changes

A completely new formatter API has been added that is much more flexible.

* Subscribe only to the events you care about.
* Methods receive notification objects rather than specific parameters,
  so new notification data can be added in a backwards compatible manner.
* Helper methods are exposed on notification objects such that inheriting
  from `BaseTextFormatter` is no longer effectively necessary.

A new formatters looks like this:

~~~ ruby
class CustomFormatter
  RSpec::Core::Formatters.register self, :example_started

  def initialize(output)
    @output = output
  end

  def example_started(notification)
    @output << "example: " << notification.example.description
  end
end
~~~

The [rspec-legacy_formatters
gem](https://github.com/rspec/rspec-legacy_formatters) is provided to continue
to support the old 2.x formatter API.

Thanks to [Jon Rowe](https://github.com/JonRowe) for taking charge of
this.

For more info:

* [Fivemat's RSpec 3 formatter (example of a full formatter implemenation)](https://github.com/tpope/fivemat/blob/3f4f550fa2852a34a020d31d834a7a3f0210b1ca/lib/fivemat/rspec3.rb)

### Assertion config changes

While most users use rspec-expectations, it's trivial to use something
else and RSpec 2.x made the most common alternate easily available via
a config option:

~~~ ruby
# spec/spec_helper.rb
RSpec.configure do |config|
  config.expect_with :stdlib
  # or, to use both:
  config.expect_with :stdlib, :rspec
end
~~~

However, there's been confusion around `:stdlib`. On Ruby 1.8, the
standard lib assertion module is `Test::Unit::Assertions`. On 1.9+ it's
a thin wrapper over `Minitest::Assertions` (and you're generally better
off using just that).  Meanwhile, there's also a test-unit gem
that defines `Test::Unit::Assertions` (which is _not_ a wrapper over
minitest) and a minitest gem.

For RSpec 3, we've removed `expect_with :stdlib` and instead opted
for explicit `:test_unit` and `:minitest` options:

~~~ ruby
# spec/spec_helper.rb
RSpec.configure do |config|
  # for test-unit:
  config.expect_with :test_unit

  # for minitest:
  config.expect_with :minitest
end
~~~

Thanks to [Aaron Kromer](http://aaronkromer.com/) for [implementing
this](https://github.com/rspec/rspec-core/pull/1466).

For more info:

* [Documentation](http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/Configuration#expect_with-instance_method)

### Define derived metadata

RSpec's metadata system is extremely flexible, allowing you to slice and
dice your test suite in many ways. There's a new config API that allows
you to define derived metadata. For example, to automatically tag all
example groups in `spec/acceptance/js` with `:js => true`:

~~~ ruby
# spec/spec_helper.rb
RSpec.configure do |config|
  config.define_derived_metadata(:file_path => %r{/spec/acceptance/js/}) do |metadata|
    metadata[:js] = true
  end
end
~~~

For more info:

* [Documentation](http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/Configuration#define_derived_metadata-instance_method)
* [rspec-core #1496 - implementation](https://github.com/rspec/rspec-core/pull/1496)
* [rspec-core #969 - original discussion](https://github.com/rspec/rspec-core/issues/969)

### Removals

Several things that are no longer core to RSpec have either been removed
entirely or extracted into an external gem:

* The Textmate formatter has been moved into the [Textmate
  bundle](https://github.com/rspec/rspec-tmbundle).
  Having a formatter for one specific text editor in rspec-core doesn't
  really make sense.
* RCov integration has been dropped. It was never updated to work with
  1.9+ and these days we recommend using
  [simplecov](https://github.com/colszowka/simplecov) instead.
* The `--debug` CLI option has been removed. These days there are many
  different debugger options, and you can activate them from the command
  line using the `--require` (or `-r`) option. For example, to use
  [byebug](https://github.com/deivid-rodriguez/byebug), pass `-rbyebug`
  at the command line.
* We've removed the `--line-number` CLI option. It had dubious semantics
  to begin with (`--line-number 43` would filter to the example defined
  near line 43 in every loaded spec file, but there's no reason line 43 in
  each file would be related), and duplicates the more terse
  `path/to/spec.rb:43` form.
* `its` has been extracted into the new
  [rspec-its](https://github.com/rspec/rspec-its) gem, which
  [Peter Alfvin](https://github.com/palfvin) has kindly offered to maintain.
* Autotest integration has been extracted into the new new
  [rspec-autotest](https://github.com/rspec/rspec-autotest) gem (which
  could use a maintainer: any volunteers?).

## rspec-expectations

### Using `should` syntax without explicitly enabling it is deprecated

In RSpec 2.11 we started the move towards eliminating monkey patching
from RSpec by [introducing a new expect-based
syntax](/blog/2012/06/rspecs-new-expectation-syntax).
In RSpec 3, we've kept the `should` syntax, and it is available by
default, but you will get a deprecation warning if you use it without
explicitly enabling it. This will pave the way for it being disabled
by default (or potentially extracted into a seperate gem) in RSpec 4,
while minimizing confusion for newcomers coming to RSpec via an old tutorial.

We consider the `expect` syntax to be the "main" syntax of RSpec now,
but if you prefer the older `should`-based syntax, feel free to keep using it:
we have no plans to ever kill it.

Thanks to [Sam Phippen](https://github.com/samphippen) for
[implementing](https://github.com/rspec/rspec-expectations/pull/326)
this.

For more info:

* [Documentation](https://relishapp.com/rspec/rspec-expectations/v/3-0/docs/syntax-configuration)

### Compound Matcher Expressions

In RSpec 3, you can chain multiple matchers together using `and` or `or`:

~~~ ruby
# these two expectations...
expect(alphabet).to start_with("a")
expect(alphabet).to end_with("z")

# ...can be combined into one expression:
expect(alphabet).to start_with("a").and end_with("z")

# You can also use `or`:
expect(stoplight.color).to eq("red").or eq("green").or eq("yellow")
~~~

These are aliased to the `&` and `|` operators:

~~~ ruby
expect(alphabet).to start_with("a") & end_with("z")
expect(stoplight.color).to eq("red") | eq("green") | eq("yellow")
~~~

Thanks to [Eloy Espinaco](https://github.com/eloyesp) for [suggesting and
implementing](https://github.com/rspec/rspec-expectations/pull/329)
this feature, and to [Adam Farhi](https://github.com/yelled3) for [extending
it](https://github.com/rspec/rspec-expectations/pull/537) with the `&` and `|` operators.

For more info:

* [New in RSpec 3: Composable Matchers](/blog/2014/01/new-in-rspec-3-composable-matchers#compound_matcher_expressions)
* [Documentation](https://relishapp.com/rspec/rspec-expectations/v/3-0/docs/compound-expectations)

### Composable Matchers

RSpec 3 allows you to expressed detailed intent by passing matchers
as arguments to other matchers:

~~~ ruby
s = "food"
expect { s = "barn" }.to change { s }.
  from( a_string_matching(/foo/) ).
  to( a_string_matching(/bar/) )

expect { |probe|
  "food".tap(&probe)
}.to yield_with_args( a_string_starting_with("f") )
~~~

For improved readability in both the code expression and failure
messages, most matchers have aliases that read properly when
passed as arguments in these sorts of expressions.

For more info:

* [New in RSpec 3: Composable Matchers](/blog/2014/01/new-in-rspec-3-composable-matchers)
* [rspec-expectations #280 - original discussion](https://github.com/rspec/rspec-expectations/issues/280)
* [rspec-expectations #393 - implementation](https://github.com/rspec/rspec-expectations/pull/393)
* [API Documentation (including list of matcher aliases)](http://rubydoc.info/github/rspec/rspec-expectations/RSpec/Matchers)
* [Relish Documentation](https://relishapp.com/rspec/rspec-expectations/v/3-0/docs/composing-matchers)

### `match` matcher can be used for data structures

Before RSpec 3, the `match` matcher existed to perform string/regex
matching using the `#match` method:

~~~ ruby
expect("food").to match("foo")
expect("food").to match(/foo/)
~~~

In RSpec 3, it additionally supports matching arbitrarily nested
array/hash data structures. The expected value can be expressed
using matchers at any level of nesting:

~~~ ruby
hash = {
  :a => {
    :b => ["foo", 5],
    :c => { :d => 2.05 }
  }
}

expect(hash).to match(
  :a => {
    :b => a_collection_containing_exactly(
      an_instance_of(Fixnum),
      a_string_starting_with("f")
    ),
    :c => { :d => (a_value < 3) }
  }
)
~~~

For more info:

* [New in RSpec 3: Composable Matchers](/blog/2014/01/new-in-rspec-3-composable-matchers#match)

### New `all` matcher

This matcher lets you specify that something is true of all items in a
collection. Pass a matcher as an argument:

~~~ ruby
expect([1, 3, 5]).to all( be_odd )
~~~

Thanks to [Adam Farhi](https://github.com/yelled3) for
[contributing](https://github.com/rspec/rspec-expectations/pull/491) this!

For more info:

* [Documentation](http://rubydoc.info/github/rspec/rspec-expectations/RSpec/Matchers#all-instance_method)

### New `output` matcher

This matcher can be used to specify that a block writes to either stdout
or stderr:

~~~ ruby
expect { print "foo" }.to output("foo").to_stdout
expect { print "foo" }.to output(/fo/).to_stdout
expect { warn  "bar" }.to output(/bar/).to_stderr
~~~

Thanks to [Matthias Günther](https://github.com/matthias-guenther) for
[suggesting](https://github.com/rspec/rspec-expectations/pull/399) this
(and for getting the ball rolling) and [Luca
Pette](https://github.com/lucapette) for [taking the feature
across the finish line](https://github.com/rspec/rspec-expectations/pull/410).

For more info:

* [Documentation](http://rubydoc.info/github/rspec/rspec-expectations/RSpec/Matchers#output-instance_method)

### New `be_between` matcher

RSpec 2 provided a `be_between` matcher for objects that implement
`between?` using the dynamic predicate support. In RSpec 3, we are
gaining a first class `be_between` matcher that is better in a few ways:

* The failure message is much better — rather than telling you that
  `between?(1, 10)` returned false, it will tell you `expected 11 to be
  between 1 and 10`.
* It works on objects that implement the comparison operators (e.g. `<`,
  `<=`, `>`, `>=`) but do not implement `between?`.
* It provides both `inclusive` and `exclusive` modes.

~~~ ruby
# like `Comparable#between?`, it is inclusive by default
expect(10).to be_between(5, 10)

# ...but you can make it exclusive:
expect(10).not_to be_between(5, 10).exclusive

# ...or explicitly label it inclusive:
expect(10).to be_between(5, 10).inclusive
~~~

Thanks to [Erik Michaels-Ober](https://github.com/sferik) for
[contributing](https://github.com/rspec/rspec-expectations/pull/405) this and
[Pedro Gimenez](https://github.com/pedrogimenez) for
[improving](https://github.com/rspec/rspec-expectations/pull/412) it!

For more info:

* [Documentation](http://rubydoc.info/github/rspec/rspec-expectations/RSpec/Matchers#be_between-instance_method)

### Boolean matchers have been renamed

RSpec 2 had a pair of matchers (`be_true` and `be_false`) that mirror
Ruby's conditional semantics: `be_true` would pass for any value besides
`nil` or `false`, and `be_false` would pass for `nil` or `false`.

In RSpec 3, we've renamed these to `be_truthy` and `be_falsey`
(or `be_falsy`, if you prefer that spelling) to make their semantics
more explicit and to reduce confusion with `be true`/`be false`
(which read the same as `be_true`/`be_false` but only pass when given
exact `true`/`false` values).

Thanks to [Sam Phippen](https://github.com/samphippen) for
[implementing](https://github.com/rspec/rspec-expectations/pull/284)
this.

For more info:

* [rspec-expectations #283 - original discussion](https://github.com/rspec/rspec-expectations/issues/283)

### `match_array` matcher now available as `contain_exactly`

RSpec has long had a matcher that allows you to match the contents of
two arrays while disregarding any ordering differences. Originally,
this was available using the `=~` operator with the old `should` syntax:

~~~ ruby
[2, 1, 3].should =~ [1, 2, 3]
~~~

Later, when we [added the `expect`
syntax](/blog/2012/06/rspecs-new-expectation-syntax),
we decided not to bring the operator matchers forward to the new syntax,
and called the matcher `match_array`:

~~~ ruby
expect([2, 1, 3]).to match_array([1, 2, 3])
~~~

`match_array` was the best name we could think of at the time
but we weren't super happy with it: "match" is an imprecise
term and the matcher is meant to work on other kinds of collections
besides arrays. We came up with a much better name for it
in RSpec 3:

~~~ ruby
expect([2, 1, 3]).to contain_exactly(1, 2, 3)
~~~

Note that `match_array` is _not_ deprecated. The two methods behave identically,
except that `contain_exactly` accepts the items splatted out individually,
whereas `match_array` accepts a single array argument.

For more info:

* [Documentation](https://relishapp.com/rspec/rspec-expectations/v/3-0/docs/built-in-matchers/contain-exactly-matcher)
* [rspec-expectations #398 - original discussion](https://github.com/rspec/rspec-expectations/issues/398)
* [Implementation](https://github.com/rspec/rspec-expectations/commit/6bde36e7b4ec67fcdd239cf498bebf07f661e561)

### Collection cardinality matchers extracted into `rspec-collection_matchers` gem

The collection cardinality matchers — `have(x).items`,
`have_at_least(y).items` and `have_at_most(z).items` — were one of
the more "magical" and confusing parts of RSpec. They have
been [extracted](https://github.com/rspec/rspec-expectations/pull/293) into the
[rspec-collection-matchers](https://github.com/rspec/rspec-collection_matchers) gem, which
[Hugo Baraúna](https://github.com/hugobarauna) has graciously volunteered to maintain.

The general alternative is to set an expectation on the size of
a collection:

~~~ ruby
expect(list).to have(3).items
# ...can be written as:
expect(list.size).to eq(3)

expect(list).to have_at_least(3).items
# ...can be written as:
expect(list.size).to be >= 3

expect(list).to have_at_most(3).items
# ...can be written as:
expect(list.size).to be <= 3
~~~

### Improved integration with Minitest

In RSpec 2.x, rspec-expectations would [automatically include
itself](https://github.com/rspec/rspec-expectations/blob/v2.14.5/lib/rspec/matchers/test_unit_integration.rb)
in `MiniTest::Unit::TestCase` or `Test::Unit::TestCase` so that
you could use rspec-expectations from Minitest or Test::Unit simply
by loading it.

In RSpec 3, we've updated this integration in a couple ways:

* Integration with Minitest 4 (or lower) or Test::Unit is no
  longer automatic. If you use rspec-expectations in such an
  environment, you'll need to `include RSpec::Matchers` yourself.
* Improved integration with Minitest 5 is now provided, but you
  have to explicitly load it via `require 'rspec/expectations/minitest_integration'`

For more info:

* [rspec/expectations/minitest\_integration.rb](https://github.com/rspec/rspec-expectations/blob/v3.0.0.beta2/lib/rspec/expectations/minitest_integration.rb)

### Changes to the matcher protocol

As mentioned above, in RSpec 3, we no longer consider `should` to be
the main syntax of rspec-expectations. We've updated the matcher
protocol to reflect this:

* `failure_message_for_should` is now `failure_message`.
* `failure_message_for_should_not` is now `failure_message_when_negated`.
* `match_for_should` (an alias of `match` in the custom matcher DSL)
  has been removed with no replacement. (Just use `match`).
* `match_for_should_not` in the custom matcher DSL is now
  `match_when_negated`.

In addition, we've added `supports_block_expectations?` as a new, optional part
of the matcher protocol. This is used to give users clear errors when they
wrongly use a value matcher in a block expectation expression. For
example, before this change, passing a block to `expect` when using a
matcher like `be_nil` could lead to false positives:

~~~ ruby
expect { foo.bar }.not_to be_nil

# ...is equivalent to:
block = lambda { foo.bar }
expect(block).not_to be_nil

# ...but the block is not nil (even though `foo.bar` might return nil),
# so the expectation will pass even though the user probably meant:
expect(foo.bar).not_to be_nil
~~~

Note that `supports_block_expectations?` is an optional part of the
protocol. For matchers that are not intended to be used in block
expectation expressions, you do not need to define it.

For more info:

* [rspec-expectations #270 - original discussion](https://github.com/rspec/rspec-expectations/issues/270)
* [rspec-expectations #373 - implementation](https://github.com/rspec/rspec-expectations/pull/373)
* [rspec-expectations #530 - original discussion of `supports_block_expectations?`](https://github.com/rspec/rspec-expectations/issues/526)
* [rspec-expectations #530 - implementation of `supports_block_expectations?`](https://github.com/rspec/rspec-expectations/pull/530)

## rspec-mocks

### Using the monkey-patched syntax without explicitly enabling it is deprecated

As with rspec-expectations, we've been moving rspec-mocks towards a
zero-monkey patching syntax. This was [originally
introduced](http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/)
in 2.14. In RSpec 3, you'll get a deprecation warning if you use the
original syntax (e.g. `obj.stub`, `obj.should_receive`, etc) without
explicitly enabling it (just like with rspec-expectations' new syntax).

Thanks to [Sam Phippen](https://github.com/samphippen) for
[implementing](https://github.com/rspec/rspec-mocks/pull/339)
this.

### `receive_messages` and `receive_message_chain` for the new syntax

The original monkey patching syntax had some features that the
new syntax, as released in 2.14, lacked. We've addressed that
in RSpec 3 via a couple new APIs: `receive_messages` and
`receive_message_chain`.

~~~ ruby
# old syntax:
object.stub(:foo => 1, :bar => 2)
# new syntax:
allow(object).to receive_messages(:foo => 1, :bar => 2)

# old syntax:
object.stub_chain(:foo, :bar, :bazz).and_return(3)
# new syntax:
allow(object).to receive_message_chain(:foo, :bar, :bazz).and_return(3)
~~~

One nice benefit of these new APIs is that they work with `expect`, too,
whereas there was no message expectation equivalent of `stub(hash)` or
`stub_chain` in the old syntax.

Thanks to [Jon Rowe](https://github.com/JonRowe) and
[Sam Phippen](https://github.com/samphippen) for implementing this.

For more info:

* [Documentation for `receive_messages`](http://rubydoc.info/github/rspec/rspec-mocks/RSpec/Mocks/ExampleMethods#receive_messages-instance_method)
* [Documentation for
  `receive_message_chain`](http://rubydoc.info/github/rspec/rspec-mocks/RSpec/Mocks/ExampleMethods#receive_message_chain-instance_method)
* [rspec-mocks #368 - discussion of `receive_messages`](https://github.com/rspec/rspec-mocks/issues/368)
* [rspec-mocks #399 - implementation of `receive_messages`](https://github.com/rspec/rspec-mocks/pull/399)
* [rspec-mocks #464 - discussion of `receive_message_chain`](https://github.com/rspec/rspec-mocks/issues/464)
* [rspec-mocks #467 - implementation of `receive_message_chain`](https://github.com/rspec/rspec-mocks/pull/467)

### Removed `mock` and `stub` aliases of `double`

Historically, rspec-mocks has provided 3 methods for creating
a test double: `mock`, `stub` and `double`. In RSpec 3, we've
removed `mock` and `stub` in favor of just `double`, and built
out more features that use the `double` nomenclature (such as
verifying doubles — see below).

Of course, while RSpec 3 no longer provides `mock` and `stub`
aliases of `double`, it's easy to define these aliases on your
own if you'd like to keep using them:

~~~ ruby
# spec/spec_helper.rb
module DoubleAliases
  def mock(*args, &block)
    double(*args, &block)
  end
  alias stub mock
end

RSpec.configure do |config|
  config.include DoubleAliases
end
~~~

Thanks to [Sam Phippen](https://github.com/samphippen) for
[implementation](https://github.com/rspec/rspec-mocks/pull/341)
this.

For more info:

* [Explanation for why we made this change](https://gist.github.com/myronmarston/6576665)

### Verifying doubles

A new type of double has been added that ensures you only stub or mock methods
that actually exist, and that passed arguments conform to the declared method
signature. The `instance_double`, `class_double`, and `object_double` doubles
will all raise an exception if those conditions aren't met. If the class has
not been loaded (usually when running a unit test in isolation), then no
exceptions will be raised.

This is a subtle behaviour, but very powerful since it allows the speed of
isolated unit tests with the confidence closer to that of an integration test
(or a type system). There is rarely a reason not to use these new more powerful
double types.

Thanks to [Xavier Shay](http://xaviershay.com) for the idea and implementation
of this feature.

For more info:

* [Blog post on motivation and uses](http://rhnh.net/2013/12/10/new-in-rspec-3-verifying-doubles)
* [Documentation](https://relishapp.com/rspec/rspec-mocks/v/3-0/docs/verifying-doubles)

### Partial double verification configuration option

Verifying double behaviour can also be [enabled globally on partial
doubles](https://relishapp.com/rspec/rspec-mocks/v/3-0/docs/verifying-doubles/partial-doubles).
(A partial double is when you mock or stub an existing object:
`expect(MyClass).to receive(:some_message)`.)

~~~ ruby
# spec/spec_helper.rb
RSpec.configure do |config|
  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
end
~~~

We recommend you enable this option for all new code.

### Scoping changes

rspec-mocks's operations are designed with a per-test lifecycle in mind.
This was documented in RSpec 2, but was not always explicitly enforced
at runtime, and we sometimes got bug reports from users when they tried
to use features of rspec-mocks outside of the per-test lifecycle.

In RSpec 3, we've tightened this up and this lifecycle is enforced
explicitly at runtime:

* Usage of rspec-mocks features from a `before(:context)` hook (or in any
  other context when there is not a current example) is not supported.
* Test doubles are only usable for one example. If you attempt to use
  a test double outside of the example in which it originated (e.g. by
  accidentally assigning it to a class attribute and then using it in
  a later example), you will get explicit errors.

We've also provided a new API that lets you create temporary scopes in
arbitrary places (such as a `before(:context)` hook):

~~~ ruby
describe MyWebCrawler do
  before(:context) do
    RSpec::Mocks.with_temporary_scope do
      allow(MyWebCrawler).to receive(:crawl_depth_limit).and_return(5)
      @crawl_results = MyWebCrawler.perform_crawl_on("http://some-host.com/")
    end # verification and resets happen when the block completes
  end

  # ...
end
~~~

Thanks to [Sam Phippen](https://github.com/samphippen) for helping with
[implementing](https://github.com/rspec/rspec-mocks/pull/449) these changes,
and [Sebastian Skałacki](https://github.com/skalee) for suggesting the new
`with_temporary_scope` feature.

For more info:

* [rspec-mocks #240 - original discussion](https://github.com/rspec/rspec-mocks/issues/240)
* [rspec-mocks #519 - `with_temporary_scope` implementation](https://github.com/rspec/rspec-mocks/pull/519)

### `any_instance` implementation blocks yield the receiver

When providing an implementation block for a method stub it can be
useful to do some calculation based on the state of the object.
Unfortunately, there wasn't a simple way to do this when using
`any_instance` in RSpec 2. In RSpec 3, the receiver is yielded
as the first argument to an `any_instance` implementation block,
making this easy:

~~~ ruby
allow_any_instance_of(Employee).to receive(:salary) do |employee, currency|
  usd_amount = 50_000 + (10_000 * employee.years_worked)
  currency.from_usd(usd_amount)
end

employee = Employee.find(23)
salary = employee.salary(Currency.find(:CAD))
~~~

Thanks to [Sam Phippen](https://github.com/samphippen) for
[implementing](https://github.com/rspec/rspec-mocks/pull/351) this.

For more info:

* [rspec-mocks #175 - original discussion](https://github.com/rspec/rspec-mocks/issues/175)

## rspec-rails

### File-type inference disabled by default

rspec-rails automatically adds metadata to specs based on their location on the
filesystem. This is confusing to new users, and not desirable for some veteran
users.

In RSpec 3, this behavior must be explicitly enabled:

~~~ ruby
# spec/spec_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 generated
configuration still enables this.

To explicitly tag specs without using automatic inference, set the `type`
metadata:

~~~ ruby
RSpec.describe ThingsController, type: :controller do
  # Equivalent to being in spec/controllers
end
~~~

The different available types are documented in each of the different spec
types, for instance [documentation for controller
specs](https://relishapp.com/rspec/rspec-rails/v/3-0/docs/controller-specs).

For more info:

* [rspec-rails #662 - original discussion](https://github.com/rspec/rspec-rails/issues/662)
* [rspec-rails #970 - implementation](https://github.com/rspec/rspec-rails/pull/970)

### Extracted activemodel mocks support

`mock_model` and `stub_model` have been extracted into the [rspec-activemodel-mocks
gem](https://github.com/rspec/rspec-activemodel-mocks).

Thanks to [Thomas Holmes](https://github.com/thomas-holmes) for doing the
extraction and for offering to maintain the new gem.

### Dropped webrat support

Webrat support has been removed. Use capybara instead.

### Anonymous controller improvements

rspec-rails has long allowed you to create anonymous controllers for testing.
In RSpec 3 they have received some improvements:

* By default they will inherit from the described class rather than
  `AppplicationController`. This behaviour can be disabled with the
  `infer_base_class_for_anonymous_controllers` configuration option.
* Many bugfixes when using in "non-standard" contexts, such as with abstract
  parents or with no `ApplicationController`. If you have had issues with
  anonymous controllers in the past, now would be a good time to try them
  again.

For more info:

* [Documentation - Anonymous controllers](https://relishapp.com/rspec/rspec-rails/v/3-0/docs/controller-specs/anonymous-controller)
* [rspec-rails #893 - Enable infering base class by default](https://github.com/rspec/rspec-rails/pull/893)
* [rspec-rails #905 - Fix anonymous controller route helpers](https://github.com/rspec/rspec-rails/pull/905)
* [rspec-rails #924 - Don't assume presence of ApplicationController](https://github.com/rspec/rspec-rails/pull/924)


## Final words

As always, full changelogs are available for each for the subprojects:

* [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)
* [rspec-rails](https://github.com/rspec/rspec-rails/blob/master/Changelog.md)

RSpec 3 is the first major release of RSpec in nearly 4 years. It
represents a huge amount of work from a large number of contributors.

We hope you like the new changes as much as we do, no matter how you use RSpec.

_Thanks to Xavier Shay for helping write this blog post and to Jon Rowe,
Sam Phippen and Aaron Kromer for proofreading it._

---

## File: source/blog/2014-06-02-rspec-2-99-0-and-3-0-0-have-been-released.html.md

---
title: RSpec 2.99.0 and 3.0.0 have been released!
author: Myron Marston
---

RSpec 2.99.0 and 3.0.0 have been released! RSpec 3 has tons of [great new
features](/blog/2014/05/notable-changes-in-rspec-3). RSpec 2.99 is
part of the [recommended upgrade path](https://relishapp.com/rspec/docs/upgrade)
for projects currently on RSpec 2.x.

RSpec 3 is the work of many, many people, and it never would have happened without
the community contributing to it. Special thanks to:

* The RSpec core team: Aaron Kromer, Andy Lindeman, Bradley Schaefer, Jon Rowe, Sam Phippen and Xavier Shay.
  It's fantastic to work with all of you.
* Yuji Nakayama, for creating [transpec](http://yujinakayama.me/transpec/).
* The folks who stepped forward to maintain the extracted gems:
  * Peter Alfvin -- [rspec-its](https://github.com/rspec/rspec-its)
  * Hugo Baraúna -- [rspec-collection_matchers](https://github.com/rspec/rspec-collection_matchers)
  * Thomas Holmes -- [rspec-activemodel-mocks](https://github.com/rspec/rspec-activemodel-mocks)
  * Abdelkader Boudih -- [rspec-autotest](https://github.com/rspec/rspec-autotest)
* Everyone who contributed to RSpec 3. Their names are all listed below.
* Everyone who tried out the betas and the release candidate. Getting bug reports early,
  before 3.0 final was out, really helped us make it a solid release, so thank you.

## The numbers

I thought it'd be fun to extract some stats from the git logs to get an idea of how much work went into RSpec 3.
I put together a [rake task](https://github.com/rspec/rspec-dev/pull/71) to do this, and the raw numbers surprised me:

### Across all repos:

* **Total Commits**: 4069
* **Merged pull requests**: 882
* **122 contributors**: Aaron Blew, Aaron Kromer, AbuSabah, Adam Farhi, Adarsh Pandit, Adrian CB, Adrian Gonzalez, Alex Peattie, Alex Rothenberg, Alex Yaremyuk, Alexander Clark, Alexey Fedorov, Alexey Pisarenko, Andy Henson, Andy Lindeman, Andy Waite, Arthur Neves, Arthur Nogueira Neves, Ashish Dixit, Ben Hamill, Ben Hoskings, Ben Moss, Ben Orenstein, Billy, Bradley Schaefer, Brandon Turner, Brian Fontenot, Cezar Halmagean, Christof, Claudio B., Damian Galarza, Daniel Fone, Daniel Murphy, Darryl Pogue, David Chelimsky, David Dollar, David Long, Eloy Espinaco, Erik Michaels-Ober, Federico Ravasio, Florian Thomas, Fujimura Daisuke, Giovanni Cappellotto, Giuseppe Capizzi, Grant Hollingworth, Guilherme Carvalho, Hendy Tanata, Hugo Baraúna, Ivo Wever, Jakub Racek, Jared Norman, Jay Hayes, Jeff Wallace, Johannes / universa1, John Feminella, John Firebaugh, John Voloski, Jon Rowe, Jonathan del Strother, Josef Šimánek, Justin Coyne, Karthik Kastury, Katsuhiko Nishimra, Keiji, Kelly Stannard, Kenrick Chien, Lucas Mazza, Marc-Andre Lafortune, MasterLambaster, Matijs van Zuijlen, Matt Sanders, Matthew M. Boedicker, Mauricio Linhares, Michael Gee, Michael de Silva, Michi Huber, Myron Marston, Nerian, Nick DeLuca, Olle Jonsson, Oren Dobzinski, Paavo Leinonen, Parker Selbert, Paul Annesley, Pedro Gimenez, Pete Higgins, Peter Alfvin, Peter Inglesby, Postmodern, Prathamesh Sonpatki, Puneet Goyal, René Föhring, Reyes Yang, Rodrigo Rosenfeld Rosas, Ryo Nakamura, Salimane Adjao Moustapha, Sam Phippen, Sergey Pchelincev, Stephen Best, Steve Richert, Stuart Hicks, Tay Ray Chuan, Thijs Wouters, Thomas Drake-Brockman, Thomas Holmes, Thomas Stratmann, Tim Cowlishaw, Tim Watson, Tom Stuart, Tom Ward, Travis Herrick, Vinicius Horewicz, Vipul A M, Xavier Shay, Yoshimi, Yuji Nakayama, lucapette, maxlinc, modocache, sanemat, thepoho, vanstee

### rspec:

* **Total Commits**: 23
* **Merged pull requests**: 3
* **5 contributors**: Aaron Kromer, Andy Lindeman, Jon Rowe, Josef Šimánek, Myron Marston

### rspec-core:


* **Total Commits**: 1589
* **Merged pull requests**: 345
* **47 contributors**: Aaron Kromer, Adam Farhi, Adrian CB, Alex Peattie, Alexander Clark, Alexey Fedorov, Andy Lindeman, Arthur Neves, Ashish Dixit, Ben Hoskings, Ben Moss, Bradley Schaefer, David Chelimsky, David Dollar, Federico Ravasio, Giuseppe Capizzi, Jay Hayes, John Feminella, Jon Rowe, Karthik Kastury, Keiji, Kelly Stannard, MasterLambaster, Matijs van Zuijlen, Matthew M. Boedicker, Michael de Silva, Michi Huber, Myron Marston, Nerian, Parker Selbert, Pete Higgins, Peter Alfvin, Postmodern, René Föhring, Ryo Nakamura, Sam Phippen, Sergey Pchelincev, Steve Richert, Tay Ray Chuan, Thomas Stratmann, Tom Stuart, Travis Herrick, Vipul A M, Xavier Shay, Yoshimi, Yuji Nakayama, thepoho

### rspec-expectations:

* **Total Commits**: 924
* **Merged pull requests**: 191
* **41 contributors**: Aaron Kromer, Adam Farhi, Adrian Gonzalez, Alexey Pisarenko, Andy Henson, Andy Lindeman, Ben Moss, Ben Orenstein, Bradley Schaefer, Brandon Turner, Claudio B., Damian Galarza, Daniel Fone, Daniel Murphy, David Chelimsky, Eloy Espinaco, Erik Michaels-Ober, Federico Ravasio, Hendy Tanata, Hugo Baraúna, Ivo Wever, Jared Norman, Jeff Wallace, John Voloski, Jon Rowe, Katsuhiko Nishimra, Kenrick Chien, Myron Marston, Nerian, Pedro Gimenez, Pete Higgins, Prathamesh Sonpatki, René Föhring, Reyes Yang, Sam Phippen, Thijs Wouters, Thomas Holmes, Xavier Shay, Yuji Nakayama, lucapette, modocache

### rspec-mocks:

* **Total Commits**: 1036
* **Merged pull requests**: 249
* **36 contributors**: Aaron Kromer, Adarsh Pandit, Andy Lindeman, Arthur Nogueira Neves, Ashish Dixit, Ben Moss, Bradley Schaefer, Cezar Halmagean, David Chelimsky, Federico Ravasio, Grant Hollingworth, Guilherme Carvalho, Jon Rowe, Jonathan del Strother, Justin Coyne, Marc-Andre Lafortune, Mauricio Linhares, Michael Gee, Michi Huber, Myron Marston, Nick DeLuca, Oren Dobzinski, Paul Annesley, Pete Higgins, René Föhring, Sam Phippen, Stephen Best, Stuart Hicks, Thomas Holmes, Tim Cowlishaw, Tom Ward, Vinicius Horewicz, Xavier Shay, Yuji Nakayama, maxlinc, sanemat

### rspec-rails:

* **Total Commits**: 497
* **Merged pull requests**: 94
* **39 contributors**: Aaron Blew, Aaron Kromer, AbuSabah, Alex Rothenberg, Alex Yaremyuk, Andy Lindeman, Andy Waite, Ben Hamill, Billy, Bradley Schaefer, Brian Fontenot, Christof, Darryl Pogue, David Long, Florian Thomas, Fujimura Daisuke, Giovanni Cappellotto, Jakub Racek, Johannes / universa1, John Firebaugh, John Voloski, Jon Rowe, Lucas Mazza, Matt Sanders, Myron Marston, Olle Jonsson, Paavo Leinonen, Peter Inglesby, Puneet Goyal, René Föhring, Rodrigo Rosenfeld Rosas, Salimane Adjao Moustapha, Sam Phippen, Thomas Drake-Brockman, Thomas Holmes, Tim Watson, Xavier Shay, Yuji Nakayama, vanstee

## Release Notes

These are just the changelogs for what's changed since RC1. The full changelogs are available on github:

* [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)
* [rspec-rails](https://github.com/rspec/rspec-rails/blob/master/Changelog.md)

### rspec-core 2.99.0

[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.99.0.rc1...v2.99.0)

Bug Fixes:

* Fix `BaseTextFormatter` so that it does not re-close a closed output
  stream. (Myron Marston)
* Use `RSpec::Configuration#backtrace_exclusion_patterns` rather than the
  deprecated `RSpec::Configuration#backtrace_clean_patterns` when mocking
  with rr. (David Dollar)

### rspec-core 3.0.0

[Full Changelog](http://github.com/rspec/rspec-core/compare/v3.0.0.rc1...v3.0.0)

Bug Fixes:

* Fix `BaseTextFormatter` so that it does not re-close a closed output
  stream. (Myron Marston)
* Fix regression in metadata that caused the metadata hash of a top-level
  example group to have a `:parent_example_group` key even though it has
  no parent example group. (Myron Marston)

Enhancements:

* Alter the default `spec_helper.rb` to no longer recommend
  `config.full_backtrace = true` see #1536 for discussion. (Jon Rowe)

### rspec-expectations 2.99.0

[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.99.0.rc1...v2.99.0)

Enhancements:

* Special case deprecation message for `errors_on` with `rspec-rails` to be more useful.
  (Aaron Kromer)

### rspec-expectations 3.0.0

[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v3.0.0.rc1...v3.0.0)

No code changes. Just taking it out of pre-release.

### rspec-mocks 2.99.0

[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.99.0.rc1...v2.99.0)

No changes. Just taking it out of pre-release.

### rspec-mocks 3.0.0

[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v3.0.0.rc1...v3.0.0)

Bug Fixes:

* Fix module prepend detection to work properly on ruby 2.0 for a case
  where a module is extended onto itself. (Myron Marston)
* Fix `transfer_nested_constants` option so that transferred constants
  get properly reset at the end of the example. (Myron Marston)
* Fix `config.transfer_nested_constants = true` so that you don't
  erroneously get errors when stubbing a constant that is not a module
  or a class. (Myron Marston)
* Fix regression that caused `double(:class => SomeClass)` to later
  trigger infinite recursion. (Myron Marston)
* Fix bug in `have_received(...).with(...).ordered` where it was not
  taking the args into account when checking the order. (Myron Marston)
* Fix bug in `have_received(...).ordered` where it was wrongly
  considering stubs when checking the order. (Myron Marston)
* Message expectation matchers now show descriptions from argument
  matchers when their expectations aren't met. (Jon Rowe)
* Display warning when encountering `TypeError` during instance method
  staging on 2.0.0-p195, suffers from https://bugs.ruby-lang.org/issues/8686
  too. (Cezar Halmagean).

### rspec-rails 2.99.0

[Full Changelog](http://github.com/rspec/rspec-rails/compare/v2.99.0.rc1...v2.99.0)

No changes. Just taking it out of pre-release.

### rspec-rails 3.0.0

[Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.0.0.rc1...v3.0.0)

Enhancements:

* Separate RSpec configuration in generated `spec_helper` from Rails setup
  and associated configuration options. Moving Rails specific settings and
  options to `rails_helper`. (Aaron Kromer)

Bug Fixes:

* Fix an issue with fixture support when `ActiveRecord` isn't loaded. (Jon Rowe)

---

## File: source/blog/2014-06-13-rspec-team-changes.html.md

---
title: RSpec Team Changes
author: Myron Marston
---

[Andy Lindeman](http://www.andylindeman.com/), who has been working on RSpec
with me for a couple years, has decided to retire from the RSpec core team.
In his current job at GitHub, he's using Ruby and Rails much less than
he used to. It has been really great to have the chance to work with Andy
over the last few years. I can't thank him enough. His work on
rspec-rails in particular (since he's been lead maintainer) has been
awesome. We wish him well in his future endeavors.

Meanwhile, [Aaron Kromer](http://aaronkromer.com/), who joined the team
a few months back, has volunteered to take responsibility as lead
rspec-rails maintainer. Aaron's already been doing a wonderful job.

Lastly, we have one more new team member -- [Yuji Nakayama](http://yujinakayama.me/).
If you've upgraded a code base from RSpec 2 to RSpec 3 you've probably
benefited from Yuji's great work on [transpec](http://yujinakayama.me/transpec/).
We're excited to have Yuji on the team.

Please join me in thanking Andy, and congratulating Aaron and Yuji!

---

## File: source/blog/2014-09-04-rspec-3-1-has-been-released.html.md

---
title: RSpec 3.1 has been released!
author: Myron Marston
---

RSpec 3.1 has just been released! Given our commitment to
[semantic versioning](http://semver.org/), this should be a trivial
upgrade for anyone already using RSpec 3.0, but if we did introduce
any regressions, please let us know, and we'll get a patch release
out with a fix ASAP.

RSpec continues to be a community-driven project with contributors
from all over the world. This release includes 647 commits from 190
pull requests from 47 different contributors.

Thank you to everyone who helped make this release happen!

## Notable Changes

### Core: Backtrace filtering changes

In RSpec 2.x and RSpec 3.0, the default backtrace filtering configuration
excluded lines from gems from printed backraces. We [got some
feedback](https://github.com/rspec/rspec-core/issues/1536#issuecomment-43521129)
that this was unhelpful and have removed `/gems/` from the default
backtrace filter patterns. In RSpec 3.1, lines from gems will be
included backtraces, but lines from RSpec itself will continue to be
excluded. Of course, if you want still gems to be excluded, you can easily
add this pattern back yourself:

~~~ ruby
# spec/spec_helper.rb
RSpec.configure do |config|
  config.backtrace_exclusion_patterns << /gems/
end
~~~

In addition, we've added a new API to make it easy to filter out one
or more specific gems:

~~~ ruby
# spec/spec_helper.rb
RSpec.configure do |config|
  config.filter_gems_from_backtrace "rack", "rake"
end
~~~

### Core: New `--exclude-pattern` option

RSpec 3.1 has a new `--exclude-pattern` option that is the inverse of
`--pattern`. This allows you to exclude particular files, so that,
for example, you can load and run all spec files except those from
a particular directory:

~~~ ruby
rspec --pattern "spec/**/*_spec.rb" --exclude-pattern "spec/acceptance/**/*_spec.rb"
~~~

The rake task definition API supports this option now, too, so it is
easy to define tasks that run all specs but those from one directory:

~~~ ruby
# Rakefile
require 'rspec/core/rake_task'

desc "Run all but the acceptance specs"
RSpec::Core::RakeTask.new(:all_but_acceptance) do |t|
  t.exclude_pattern = "spec/acceptance/**/*_spec.rb"
end
~~~

Thanks to John Gesimondo for suggesting and
[implementing](https://github.com/rspec/rspec-core/pull/1651)
this new feature!

### Core: Can now be used standalone without configuration

RSpec got split up into separate gems (core, expecations and mocks) in RSpec 2.0,
which allows users to [mix and
match parts of RSpec](/blog/2012/07/mixing-and-matching-parts-of-rspec)
with other testing libraries like Minitest. Tom Stuart pointed out that it
wasn't as easy to use just rspec-core as it could be--specifically, in RSpec 3.0 and
before, if you didn't explicitly configure rspec-core to not use
rspec-expectations and rspec-mocks, it assumed they were available,
tried to load them, and gave you an error if they were not.

In RSpec 3.1, we've rectified this. rspec-expectations and rspec-mocks
will still both be used by default if available, but it they are not
available and you haven't configured anything, rspec-core will work just
fine.

Thanks to Sam Phippen for [implementating](https://github.com/rspec/rspec-core/pull/1615) this improvement.

### Core: Warnings flag no longer defaults to true in generated files

In RSpec 3.0, we put `--warnings` in the generated `.rspec` file. We
did that to encourage gem authors to make their gems warning-free (as
gems that issue warnings inhibit users from using Ruby's warning mode).
However, the rails ecosystem has generally not strived to have warning-free
code, and on new rails projects, this led to a _ton_ of confusing warnings.

In RSpec 3.1, we learned from the community feedback on this and have removed
`--warnings` from the generated `.rspec` file. In non-rails projects, `rspec --init`
will include `config.warnings = true` in the commented-out section of recommended
settings in `spec_helper.rb`.

Thanks to Andrew Hooker for [making this change](https://github.com/rspec/rspec-core/pull/1572).

### Expectations: New `have_attributes` matcher

This new matcher makes it easy to match an object based on its attributes:

~~~ ruby
Person = Struct.new(:name, :age)
person = Person.new("Coen", 3)
expect(person).to have_attributes(name: "Coen", age: 3)
~~~

It's also aliased to `an_object_having_attributes`, which is particularly
useful in composed matcher expressions:

~~~ ruby
people = [Person.new("Coen", 3), Person.new("Daphne", 2)]
expect(people).to match([
  an_object_having_attributes(name: "Coen",   age: 3),
  an_object_having_attributes(name: "Daphne", age: 2)
])
~~~

It can also be used as an argument matcher for a message expectation:

~~~ ruby
expect(email_gateway).to receive(:send_receipt).with(
  an_object_having_attributes(email: "foo@example.com")
)
~~~

Thanks to Adam Farhi for
[implementing](https://github.com/rspec/rspec-expectations/pull/571)
this new matcher.

### Expectations: Block matchers can now be used in compound expressions

RSpec 3.0 gained the ability to use [compound matcher
expressions](/blog/2014/01/new-in-rspec-3-composable-matchers#compound_matcher_expressions).
However, it didn't work with block expectations because we had internal
changes that needed to be made to ensure the block is only executed
once as one would expect. We've addressed this in 3.1, which allows an
expression like:

~~~ ruby
x = y = 0
expect {
  x += 1
  y += 2
}.to change { x }.to(1).and change { y }.to(2)
~~~

### Expectations: New `define_negated_matcher` API

This new API provides a means to define a negated version of an existing matcher:

~~~ ruby
# define a negated form of `include`...
RSpec::Matchers.define_negated_matcher :exclude, :include

# ...which allows you to write:
expect(odd_numbers).to exclude(14)

# ...rather than:
expect(odd_numbers).not_to include(14)
~~~

On its own, this doesn't buy you much. However, it really comes in handy
when dealing with composed or compound matcher expressions:

~~~ ruby
adults = Town.find("Springfield").adults
marge  = Character.find("Marge")
bart   = Character.find("Bart")

expect(adults).to include(marge).and exclude(bart)
~~~

Thanks to Adam Farhi for helping with the
[implementation](https://github.com/rspec/rspec-expectations/pull/618)
of this feature.

### Expectations: Custom matcher chained modifiers now included in generated description

The custom matcher DSL allows you to define a fluent interface using
`chain`:

~~~ ruby
RSpec::Matchers.define :be_smaller_than do |max|
  chain :and_bigger_than do |min|
    @min = min
  end

  match do |actual|
    actual < max && actual > @min
  end
end

# usage:
expect(10).to be_smaller_than(20).and_bigger_than(5)
~~~

In RSpec 2.x and 3.0, the chained part was not included in failure messages:

~~~
Failure/Error: expect(5).to be_smaller_than(10).and_bigger_than(7)
  expected 5 to be smaller than 10
~~~

RSpec 3.1 can include the chained part in the failure message:

~~~
Failure/Error: expect(5).to be_smaller_than(10).and_bigger_than(7)
  expected 5 to be smaller than 10 and bigger than 7
~~~

...but only if you enable this behavior with a config option:

~~~ ruby
RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end
end
~~~

This config option defaults to `false` for backwards compatibility.
We plan to always enable it in RSpec 4.

Thanks to Dan Oved for
[implementing](https://github.com/rspec/rspec-expectations/pull/600)
this improvement!

### Mocks: New `*_spy` methods

RSpec 2.14 added support for using test doubles as spies, which allow
you to set an expectation that a message was received after the fact:

~~~ ruby
spy = double(:foo => nil)
# do something with spy
expect(spy).to have_received(:foo)
~~~

Note that we stubbed `foo` here. This is necessary because doubles are
strict by default -- meaning that they will raise an error when they
receive an unexpected message. Unfortunately, this forces a bit of
duplication on you as you have to declare the method twice (stubbing it
once before and expecting it was received after).

You can get around this by using `as_null_object` which makes a double
"loose" rather than strict, allowing it to receive any message:

~~~ ruby
spy = double.as_null_object
# do something with spy
expect(spy).to have_received(:foo)
~~~

This pattern is useful enough that in RSpec 3.1, we've added new methods
to declare spies:

~~~ ruby
spy(...)          # equivalent to double(...).as_null_object
instance_spy(...) # equivalent to instance_double(...).as_null_object
class_spy(...)    # equivalent to class_double(...).as_null_object
object_spy(...)   # equivalent to object_double(...).as_null_object
~~~

Thanks to Justin Searls for [bringing
up this issue](https://github.com/rspec/rspec-mocks/issues/636) and
Sam Phippen for
[implementing](https://github.com/rspec/rspec-mocks/pull/671) the new
methods.

### Mocks: New `and_wrap_original` API

This new API allows you to easily decorate a particular existing method on a
particular object just for the duration of the current example. The
original method is yielded to your block as the first argument (before
the args of the actual method call).

~~~ ruby
allow(api_client).to receive(:fetch_users).and_wrap_original do |original_method, *args|
  original_method.call(*args).first(10) # truncate the response to the first 10 users
end
~~~

Thanks to Jon Rowe for
[implementing](https://github.com/rspec/rspec-mocks/pull/762) this
feature.

### Rails: Rails 4.2 support

rspec-rails 3.1 will officially support Rails 4.2. Aaron Kromer has been
doing a great job getting RSpec 3.1 ready for Rails 4.2. This includes
a generator [provided by Abdelkader
Boudih](https://github.com/rspec/rspec-rails/pull/1155) for ActiveJob.

### Rails: Generated `rails_helper.rb` no longer auto-loads `spec/support` files by default

Aaron has also [made a small change](https://github.com/rspec/rspec-rails/pull/1137)
to the generator for `rails_helper.rb`.  Previously, it contained some code that
would automatically load all files under `spec/support`. That code is still
there but is now commented out.  We've found that it helps prevent load time
bloat to manually require the support files that are needed, rather than
always loading all of them.

Of course, if you prefer the convenience of the old way, that's a reasonable
tradeoff, and you can easily uncomment this bit of code.

## Stats

### rspec-core:

* **Total Commits**: 176
* **Merged pull requests**: 50
* **20 contributors**: Aaron Kromer, Alex Tan, Andrew Hooker, Christian Treppo, Colin Jones, Daniela Wellisz, Dominic Muller, Evgeny Zislis, Gary Fleshman, Jimmy Cuadra, John Gesimondo, Jon Rowe, Mark Lorenz, Max Lincoln, Myron Marston, Paul Cortens, Prem Sichanugrist, Sam Phippen, Su Zhang (張甦), tomykaira

### rspec-expectations:

* **Total Commits**: 149
* **Merged pull requests**: 40
* **14 contributors**: Aaron Kromer, Abdelkader Boudih, Adam Farhi, Alex Sunderland, Chris Griego, Dennis Taylor, Hao Su, Jon Rowe, Myron Marston, Pritesh Jain, Sam Phippen, Xavier Shay, fimmtiu, oveddan

### rspec-mocks:

* **Total Commits**: 118
* **Merged pull requests**: 39
* **13 contributors**: Aaron Kromer, Chris Griego, Dennis Taylor, Eugene Kenny, Igor Kapkov, Jimmy Cuadra, Jon Rowe, Karthik T, Myron Marston, Oliver Martell Núñez, Sam Phippen, Thomas Brand, Xavier Shay

### rspec-rails:

* **Total Commits**: 137
* **Merged pull requests**: 38
* **16 contributors**: Aaron Kromer, Abdelkader Boudih, Alex Rothenberg, Andre Arko & Doc Ritezel, André Arko, Bradley Schaefer, Diego Plentz, Jon Rowe, Josh Kalderimis, Juan González, Kosmas Chatzimichalis, Michael E. Gruen, Myron Marston, Sam Phippen, Thomas Kriechbaumer, joker1007

### rspec-support:

* **Total Commits**: 67
* **Merged pull requests**: 23
* **8 contributors**: Aaron Kromer, Ben Langfeld, Jimmy Cuadra, Jon Rowe, Myron Marston, Pritesh Jain, Sam Phippen, Xavier Shay

## Docs

### API Docs

* [http://rubydoc.info/gems/rspec-core](http://rubydoc.info/gems/rspec-core)
* [http://rubydoc.info/gems/rspec-expectations](http://rubydoc.info/gems/rspec-expectations)
* [http://rubydoc.info/gems/rspec-mocks](http://rubydoc.info/gems/rspec-mocks)
* [http://rubydoc.info/gems/rspec-rails](http://rubydoc.info/gems/rspec-rails)

### Cucumber Features

* [http://relishapp.com/rspec/rspec-core](http://relishapp.com/rspec/rspec-core)
* [http://relishapp.com/rspec/rspec-expectations](http://relishapp.com/rspec/rspec-expectations)
* [http://relishapp.com/rspec/rspec-mocks](http://relishapp.com/rspec/rspec-mocks)
* [http://relishapp.com/rspec/rspec-rails](http://relishapp.com/rspec/rspec-rails)


## Release Notes

### rspec-core-3.1.0
[Full Changelog](http://github.com/rspec/rspec-core/compare/v3.0.4...v3.1.0)

Enhancements:

* Update files generated by `rspec --init` so that warnings are enabled
  in commented out section of `spec_helper` rather than `.rspec` so users
  have to consciously opt-in to the setting. (Andrew Hooker, #1572)
* Update `spec_helper` generated by `rspec --init` so that it sets the new
  rspec-expectations `include_chain_clauses_in_custom_matcher_descriptions`
  config option (which will be on by default in RSpec 4) and also sets the
  rspec-mocks `verify_partial_doubles` option (which will also default
  to on in RSpec 4). (Myron Marston, #1647)
* Provide an `inspect` output for example procsy objects (used in around
  hooks) that doesn't make them look like procs. (Jon Rowe, #1620)
* Remove a few unneeded `require` statements from
  `rspec/core/rake_task.rb`, making it even more lighterweight.
  (Myron Marston, #1640)
* Allow rspec-core to be used when neither rspec-mocks or
  rspec-expectations are installed, without requiring any
  user configuration. (Sam Phippen, Myron Marston, #1615)
* Don't filter out gems from backtraces by default. (The RSpec
  gems will still be filtered). User feedback has indicated
  that including gems in default backtraces will be useful.
  (Myron Marston, #1641)
* Add new `config.filter_gems_from_backtrace "rack", "rake"` API
  to easily filter the named gems from backtraces. (Myron Marston, #1682)
* Fix default backtrace filters so that the RSpec binary is
  excluded when installing RSpec as a bundler `:git` dependency.
  (Myron Marston, #1648)
* Simplify command generated by the rake task so that it no longer
  includes unnecessary `-S`. (Myron Marston, #1559)
* Add `--exclude-pattern` CLI option, `config.exclude_pattern =` config
  option and `task.exclude_pattern =` rake task config option. Matching
  files will be excluded. (John Gesimondo, Myron Marston, #1651, #1671)
* When an around hook fails to execute the example, mark it as
  pending (rather than passing) so the user is made aware of the
  fact that the example did not actually run. (Myron Marston, #1660)
* Remove dependency on `FileUtils` from the standard library so that users do
  not get false positives where their code relies on it but they are not
  requiring it. (Sam Phippen, #1565)

Bug Fixes:

* Fix rake task `t.pattern =` option so that it does not run all specs
  when it matches no files, by passing along a `--pattern` option to
  the `rspec` command, rather than resolving the file list and passing
  along the files individually. (Evgeny Zislis, #1653)
* Fix rake task default pattern so that it follows symlinks properly.
  (Myron Marston, #1672)
* Fix default pattern used with `rspec` command so that it follows
  symlinks properly. (Myron Marston, #1672)
* Change how we assign constant names to example group classes so that
  it avoids a problem with `describe "Core"`. (Daniela Wellisz, #1679)
* Handle rendering exceptions that have a different encoding than that
  of their original source file. (Jon Rowe, #1681)
* Allow access to message_lines without colour for failed examples even
  when they're part of a shared example group. (tomykaira, #1689)


### rspec-expectations-3.1.0
[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v3.0.4...v3.1.0)

Enhancements:

* Add `have_attributes` matcher, that passes if actual's attribute
  values match the expected attributes hash:
  `Person = Struct.new(:name, :age)`
  `person = Person.new("Bob", 32)`
  `expect(person).to have_attributes(:name => "Bob", :age => 32)`.
  (Adam Farhi, #571)
* Extended compound matcher support to block matchers, for cases like:
  `expect { ... }.to change { x }.to(3).and change { y }.to(4)`. (Myron
  Marston, #567)
* Include chained methods in custom matcher description and failure message
  when new `include_chain_clauses_in_custom_matcher_descriptions` config
  option is enabled. (Dan Oved, #600)
* Add `thrice` modifier to `yield_control` matcher as a synonym for
  `exactly(3).times`. (Dennis Taylor, #615)
* Add `RSpec::Matchers.define_negated_matcher`, which defines a negated
  version of the named matcher. (Adam Farhi, Myron Marston, #618)
* Document and support negation of `contain_exactly`/`match_array`.
  (Jon Rowe, #626).

Bug Fixes:

* Rename private `LegacyMacherAdapter` constant to `LegacyMatcherAdapter`
  to fix typo. (Abdelkader Boudih, #563)
* Fix `all` matcher so that it fails properly (rather than raising a
  `NoMethodError`) when matched against a non-enumerable. (Hao Su, #622)


### rspec-mocks-3.1.0
[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v3.0.4...v3.1.0)

Enhancements:

* Add spying methods (`spy`, `ìnstance_spy`, `class_spy` and `object_spy`)
  which create doubles as null objects for use with spying in testing. (Sam
  Phippen, #671)
* `have_received` matcher will raise "does not implement" errors correctly when
  used with verifying doubles and partial doubles. (Xavier Shay, #722)
* Allow matchers to be used in place of keyword arguments in `with`
  expectations. (Xavier Shay, #726)
* Add `thrice` modifier to message expectation interface as a synonym
  for `exactly(3).times`. (Dennis Taylor, #753)
* Add more `thrice` synonyms e.g. `.at_least(:thrice)`, `.at_most(:thrice)`,
  `receive(...).thrice` and `have_received(...).thrice`. (Jon Rowe, #754)
* Add `and_wrap_original` modifier for partial doubles to mutate the
  response from a method. (Jon Rowe, #762)

Bugfixes:

* Remove `any_number_of_times` from `any_instance` recorders that were
  erroneously causing mention of the method in documentation. (Jon Rowe, #760)
* Prevent included modules being detected as prepended modules on Ruby 2.0.
  (Eugene Kenny, #771)


### rspec-rails-3.1.0
[Full Changelog](http://github.com/rspec/rspec-rails/compare/v3.0.2...v3.1.0)

Enhancements:

* Switch to using the `have_http_status` matcher in spec generators. (Aaron Kromer, #1086)
* Update `rails_helper` generator to allow users to opt-in to auto-loading
  `spec/support` files instead of forcing it upon them. (Aaron Kromer, #1137)
* Include generator for `ActiveJob`. (Abdelkader Boudih, #1155)
* Improve support for non-ActiveRecord apps by not loading ActiveRecord related
  settings in the generated `rails_helper`. (Aaron Kromer, #1150)
* Remove Ruby warnings as a suggested configuration. (Aaron Kromer, #1163)

Bug Fixes:

* Fix controller route lookup for Rails 4.2. (Tomohiro Hashidate, #1142)

---

## File: source/blog/2015-01-29-new-rspec-website.html.md

---
title: New RSpec Website!
author: Myron Marston
---

RSpec's website has been in need of a refresh for a long time. We've
been working on this new site, off and on, for more than a year, and
we're glad to finally ship it. We hope that it'll prove much
more useful to the community than the old site, particularly since it
now hosts our [documentation](/documentation) and our [blog](/blog).

I'd like to thank all the people who helped make this site happen:

* [Ninefold](https://ninefold.com/), who sponsored the development of
  the site and are covering its on-going costs.
* [Katie Chen](http://pistachiomade.com/), who came up with the logo and
  new design.
* [Andrew Harvey](http://mootpointer.com/),
  [Shamim Jahandideh](https://github.com/sjahandideh), and
  [Jon Rowe](http://jonrowe.co.uk/), who helped develop the site.
* [Carlos Rodriguez](http://cohitre.com/) and Brandon Renfrow, who helped out with the CSS.

While what we have now is a huge improvement, it's still not as polished
as we would like, and we're hoping folks from the community will chip in
and help us iteratively improve it. The blog in particular -- which I
helped put together -- is badly in need of some CSS improvements, but my
CSS skills are very poor.

If you'd like to help us out, head over to the [GitHub
repo](https://github.com/rspec/rspec.github.io) and either open an issue
to suggest improvements or submit a pull request.

---

## File: source/blog/2015-01-30-new-gem-signing-certificate.html.md

---
title: New RSpec Gem signing certificate
author: Sam Phippen
---

**TL;DR If you rely on our signing of RSpec releases you'll have to get a new cert from us**

For the upcoming release of RSpec 3.2 we've created a new signing certificate
for the RSpec gems. The reason for this change is that
[our old certificate](https://github.com/rspec/rspec/blob/6af4995482ade2d49ad361ee003dee29f713ab17/certs/rspec.pem)
expired. Rubygems certificates have a 1 year expiry by default. The new certificate can be found
[on GitHub](https://github.com/rspec/rspec/blob/858e0c2ac849d941bfd5b3a5c5e04a4f596fe666/certs/rspec.pem)
and has a 10 year expiry, so you can expect it to be used to verify all of the
RSpec gems for a while. The expiry of our old certificate means there won't be
any more RSpec 3.0.x or 3.1.x releases as we don't want to sign them with
conflicting certificates.

With the new certificate comes a new way of our end users ensuring that the
certificate is the correct one. A number of the RSpec core team members
will be adding [detatched GPG signatures](https://www.gnupg.org/gph/en/manual.html#AEN161) to
the core RSpec gem repository. This way, if you meet one of them in real life, you can
validate that the certificate that you have is the same one we hosted. The first signature,
[mine](https://github.com/rspec/rspec/blob/858e0c2ac849d941bfd5b3a5c5e04a4f596fe666/certs/samphippen.asc), is
available on GitHub now. If I meet you at any conference, I'll be happy to do a key signing
with you so that you can ensure that you've got the real certificate.

Over the next few months, we'll be adding more signatures from other members of
the core team so that it is easier for you to validate the certificate.

## How does this affect me?

This only affects people that already use the Rubygems signing security feature
for RSpec. If you've never checked the certificate you don't need to do anything.
If you are using the old RSpec certificate you'll need to move to the new one.