Guichi Ren
Guichi Ren

Reputation: 67

spec run the same set of tests with different configuration

Assume a spec file that contains a number of tests:

before(:all) do
   @object = buildObjectA
end

it 'should compute x correctly' do
   test something based on object
end

it 'should compute y correctly' do
   test something based on object
end

I wanted to do the same set of tests but with a different configuration, for example, in before(:all), it looks like this:

before(:all) do
   @object = buildObjectB
end

What is the best way of doing this?

Upvotes: 1

Views: 341

Answers (2)

mhutter
mhutter

Reputation: 2916

You can use Shared Examples and Contexts:

RSpec.shared_examples "something" do |x|
  it 'should compute x correctly' do
    test something based on object
  end

  it 'should compute y correctly' do
    test something based on object
  end
end

RSpec.describe "A" do
  include_examples "something", buildObjectA
end

RSpec.describe "B" do
  include_examples "something", buildObjectB
end

(given your tests are all the same for both objects)

Upvotes: 1

Petr Gazarov
Petr Gazarov

Reputation: 3821

I think you'll want to use context. Is is just like describe but has a more semantic name which better fits a situation like yours.

context 'when object is A' do
  before(:all) do
    @object = buildObjectA
  end

  it 'should compute x correctly' do
    test something based on object
  end

  it 'should compute y correctly' do
    test something based on object
  end
end

context 'when object is B' do
  before(:all) do
    @object = buildObjectB
  end

  it 'should compute x correctly' do
    test something based on object
  end

  it 'should compute y correctly' do
    test something based on object
  end
end

When your test fails, it will chain all describe, context and it arguments and give you the full description of your test example.

Upvotes: 0

Related Questions