Parametrized shared example groups in RSpec

RSpec 2

In RSpec 2 shared_examples_for can have parameters Show archive.org snapshot . You can simply hand over arguments from it_should_behave_like:

shared_examples_for 'string equaling another string' do |expected_string|
  it 'should be equal to another string' do
    subject.should == expected_string
  end
end

describe 'some string' do
  subject { 'foo' }
  it_should_behave_like 'string equaling another string', 'foo'
end

RSpec 1

Use it_should_act_like from our spec_candy.rb (note the /behave/act/). It allows you to call a standard shared example group with parameters.

Some stupid examples follow to show how it works:

shared_examples_for 'string equaling another string' do
  it 'should be equal to another string' do
    subject.should == string
  end
end

describe 'some string' do
  subject { 'foo' }
  it_should_act_like 'string equaling another string', :string => 'foo'
end

If you call it_should_act_like with a block, it will be made available as block:

shared_examples_for 'action requiring admin user' do
  it 'should deny access to a guest user' do
    sign_in 'guest'
    expect { block.call }.to raise_error(Aegis::AccessDenied)
  end
end

describe UsersController do
  describe '#new' do
    it_should_act_like 'action requiring admin user' do
      get :new
    end
  end
end
Henning Koch Over 13 years ago