joao
joao

Reputation: 3566

Rewrite shared example groups in rspec2

In rspec 1 I could do

describe "Something", :shared => true do
 include SomeModule # which has the :a_method method

 def a_method(options)
   super(options.merge(:option => @attr)
 end

 it "foofoofoo" do
 end
end

describe "Something else" do
  before(:each) do
    @attr = :s_else
  end

  it_should_behave_like "Something"

  it "barbarbar" do
    a_method(:name => "something else")
    Something.find("something else").name.should == "Something else"
  end
...
end

That is, I could use :shared => true to not only refactor examples but also share method definitions and attributes. I realize the example is contrived, but how would one write it in rspec >= 2 without touching the SomeModule module or the Something class?

Upvotes: 1

Views: 1121

Answers (1)

zetetic
zetetic

Reputation: 47548

You can do this with shared_examples_for

shared_examples_for "something" do
  include SomeModule # which has the :a_method method

  def a_method(options)
    super(options.merge(:option => @attr))
  end

  it "foofoofoo" do
  end
end

And call with it_behaves_like:

it_behaves_like "something"

EDIT

Joao correctly points out that this fails to include SomeModule for the examples in the describe block. The include would have to take place outside the shared example group, e.g. at the top of the spec file

include SomeModule # which has the :a_method method

# ...

shared_examples_for "something" do
  def a_method(options)
    super(options.merge(:option => @attr))
  end

  it "foofoofoo" do
  end
end

David Chelimsky discusses some new features of shared examples in RSpec 2 which may be pertinent in this blog post.

Upvotes: 2

Related Questions