Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dchelimsky/727112 to your computer and use it in GitHub Desktop.
Save dchelimsky/727112 to your computer and use it in GitHub Desktop.
shared_example_group_rspec_2_workaround
# shared example groups in rspec-1 are evaluated in the example group that
# has it_should_behave_like.
#
# This behavior changed in rspec-2, in which it_should_behave_like generates a
# nested group. This means that a structure like this won't work as you expect
# in rspec-2
#
# shared_examples_for "logged in as admin" do
# before { login_as :admin }
# end
#
# describe AdminController do
# it_should_behave_like "logged in as admin"
#
# it "GET index renders the index template" do
# get :index
# response.should render_template("index")
# end
# end
#
# In this ^^ example, the before block is _not_ run in the same group as
# it "GET index renders the index template" in rspec-2.
#
# If you have shared groups in an rspec-1 suite that you are upgrading, you can
# use either of these workarounds:
#
# Workaround #1 - requires no changes to spec code, but changes the behavior
# of rspec-2 shared groups.
module SharedExampleGroupWorkaround
def it_should_behave_like(name, *args, &block)
if args.empty? && block.nil?
module_eval(&world.shared_example_groups[name])
else
super
end
end
end
RSpec.configure do |config|
config.extend SharedExampleGroupWorkaround
end
# Workaround #2 - requires changing existing instances of it_should_behave_like
# to include_shared_context, but does not change the way it_should_behave_like works
# in rspec-2. This is likely to be added directly to rspec-core, so I'd recommend
# this option:
module SharedExampleGroupWorkaround
def include_shared_context(name)
module_eval(&world.shared_example_groups[name])
end
end
RSpec.configure do |config|
config.extend SharedExampleGroupWorkaround
end
@myronmarston
Copy link

FWIW, I've been sharing before/after hooks by defining a method in a module, exending the module in RSpec.configure, and then calling the method in an example group.

I may switch to something like include_shared_context in the future but this has worked nicely for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment