RSpec : Shared example group (it_behaves_like , include_examples , shared_examples )

You probably know how to use describe, context, it and specify to clearly communicate one aspect of your code. The nested context provides by it_behaves_like can be used to improve this communication with the reader.

I will base my example on the example given in the RSpec documentation for shared examples:

shared_examples "a collection" do
  context "initialized with 3 items" do
    it "says it has three items" do
      # ...

describe Array do
  it_behaves_like "a collection"
  include_examples "a collection"

If you run RSpec with --format documentation you get the following output:

  behaves like a collection
    initialized with 3 items
      says it has three items
  initialized with 3 items
    says it has three items

So the difference is how the spec is read eg in case of a failure.

Which style you prefer is a question of aesthetics of how you like your specs to read. Furthermore you would suggest to always use the same style if you work in a team to improve consistency.

Also, are it_should_behave_like and it_behaves_like just synonyms?

Almost, the context is named differently. it should behave like ... vs behaves like .... Again a question of aesthetics.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s