Lachlan Cotter
Lachlan Cotter

Reputation: 1889

RSpec shared examples must not be shared

This took me by surprise…

Seems that you can’t use the same name for 2 rspec shared example groups anywhere within your project. If you do, then when you run rake spec (to run all the specs), then rspec complains that a shared example group was declared with a non-unique name.

This happens even when the calls to shared_examples_for are contained within a describe block (one would presume that should scope the examples).

At first I tried to work around this by changing the names of the example groups (not ideal, but I can live with it).

But this became more of a problem when I wanted to factor out the example group to a separate file so I could share it between multiple spec files.

The specs work okay when run in isolation, but when I run the suite, rspec complains.

`ensure_shared_example_group_name_not_taken': \
Shared example group 'a person' already exists (ArgumentError)

Surely this is a common problem.

Is there something I’m missing here?

Upvotes: 13

Views: 6308

Answers (2)

clacke
clacke

Reputation: 8016

There are some tips in the official documentation on how best to handle this:

https://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples

TL;DR

Yes, shared examples are global. Best practice for Ruby On Rails: Place shared examples in spec/support/foo_bar_shared_examples.rb and just start writing shared_example straight, without wrapping in any describe block or otherwise.

Upvotes: 2

David Chelimsky
David Chelimsky

Reputation: 9000

As of rspec 2.6, shared examples are global. You can declare them in an example group, but they are not scoped to that group.

Upvotes: 12

Related Questions