13

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?

2 Answers 2

12

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.

4
  • Thanks David. Any recommendation as to how to use shared examples in more than one spec file? It seems that calling shared_examples_for outside of a describe block causes rake to fail. Jul 26, 2011 at 15:09
  • Sorry. That's not true. It fails even when I wrap it in describe. Apparently it's something to do with requiring another file. Jul 26, 2011 at 15:12
  • 4
    The intent is to define them in one file and use them in n other files, so it should definitely work if you have them in a different file. The convention is to keep them in a file under spec/support (e.g. spec/support/shared_examples_for_xyz.rb) and require those files from spec/spec_helper.rb. Jul 27, 2011 at 2:09
  • Thanks David. Placing the shared examples in the support dir and requiring from spec_helper did the trick. Jul 29, 2011 at 16:03
2

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.