[rspec-users] how to include module into shared example group in RSpec 2

David Chelimsky dchelimsky at gmail.com
Wed Jun 1 10:42:28 EDT 2011


On Jun 1, 2011, at 9:10 AM, Jarmo Pertman wrote:

> Hi!
> 
> We tried to upgrade our RSpec from 1.3.1 to 2.6 and are having some
> problems. It seems that shared example group includes modules
> differently in RSpec 2.
> 
> Consider the following code:
> module MyModule
>  def testing
>  end
> end
> 
> shared_examples_for "shared" do
>  include MyModule
> 
>  it "works" do
>    testing
>  end
> end
> 
> describe "describe" do
>  it_should_behave_like "shared"
> 
>  it "works too" do
>    testing
>  end
> end
> 
> When running with RSpec 1.3.1 all specs are passing, but RSpec 2.6
> fails with one failure:
>  1) describe works too
>     Failure/Error: testing
>     NameError:
>       undefined local variable or method `testing' for
> #<RSpec::Core::ExampleGroup::Nested_1:0x47edee0 @example=nil>
>     # ./spec/blah/blah_spec.rb:18
> 
> It seems that the describe block doesn't get the methods included from
> the module. How to solve that problem?

This has been through a bit of churn, but here is the short version:

it_should_behave_like creates (and wraps) a nested group, but there is are also two new include_context/include_examples methods. Your choices are:

describe "describe" do
  it_should_behave_like "shared" do
    it "works too" do
      testing
    end
  end
end

describe "describe" do
  include_context "shared"
  it "works too" do
    testing
  end
end

describe "describe" do
  include_examples "shared"
  it "works too" do
    testing
  end
end


More information about the rspec-users mailing list