Read more

Parametrized shared example groups in RSpec

Henning Koch
December 16, 2010Software engineer at makandra GmbH

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

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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
Posted by Henning Koch to makandra dev (2010-12-16 19:53)