Parametrized shared example groups in RSpec

Updated . Posted . Visible to the public.

RSpec 2

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

shared_examples_for 'string equaling another string' do |expected_string|
  it 'is equal to another string' do
    expect(subject).to eq(expected_string)
  end
end

describe 'some string' do
  subject { 'foo' }
  it_behaves_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
Last edit
Daniel Straßner
Keywords
it_should_behave_like
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2010-12-16 18:53)