Difference between shared_examples and shared_context

101 views
Skip to first unread message

Arup Rakshit

unread,
Jul 2, 2014, 3:31:42 PM7/2/14
to rs...@googlegroups.com
Hi,

I am having hard time to understand what are the situations I need to think
about shared_context instead of shared_examples. From the doco of
shared_examples https://relishapp.com/rspec/rspec-core/v/3-0/docs/example-groups/shared-examples.

shared_context doco is not much clear about its actual use-cases. Can anyone
highlight me telling the use-case wise difference between these 2 ?

--
================
Regards,
Arup Rakshit
================
Debugging is twice as hard as writing the code in the first place. Therefore,
if you write the code as cleverly as possible, you are, by definition, not
smart enough to debug it.

--Brian Kernighan

Myron Marston

unread,
Jul 2, 2014, 4:12:48 PM7/2/14
to rs...@googlegroups.com
Implementation wise, they are actually identical: both declare a named block of example group code that can later be included in any other example group.  In fact, they are simply aliases:


Where the difference comes in is in how you include them: `it_behaves_like` (and `it_should_behave_like`, an alias) defines a nested example group, and then eval's the shared group block in that context, where as `include_context` or `include_examples`, eval the block directly in the including context.  Generally for shared examples you want the former, but for context sharing you'll want the latter, as the point is explicitly to share the context stuff (before hooks, helper methods, etc).

As for when to use one vs the other: use `shared_examples` when you've got some common examples you want to share.  Use `shared_context` when you've got some common context stuff you want to share, such as helper methods, before hooks, etc.

HTH,
Myron
Reply all
Reply to author
Forward
0 new messages