Tom Rossi
Tom Rossi

Reputation: 12066

Running the same test multiple times with different setups

Does anyone know of a nice dry way to run the same group of tests in different contexts. Here is a ridiculous example of wanting to run the same tests with two different setups. I don't want to have to repeat the same tests just so I can have different setups.

context 'cat' do
  setup do
    @object = cat
    ....
  end

  should 'walk' do
    assert @object.walk?
    ...
  end

  should 'run' do
    assert @object.run?
    ...
  end
end

context 'dog' do
  setup do
    @object = dog
    ....
  end

  should 'walk' do
    assert @object.walk?
    ...
  end

  should 'run' do
    assert @object.run?
    ...
  end
end

Upvotes: 2

Views: 1038

Answers (1)

Shadwell
Shadwell

Reputation: 34774

I've done it with merge_block before. Define a class method in your test that returns a Proc of your shoulds and then merge it in where appropriate.

def self.walk_and_run
  Proc.new do
    should 'walk' do
      assert @object.walk?
    end
    should 'run' do
      assert @object.run?
    end
  end
end

context 'cat' do
  setup do
    @object = cat
  end
  merge_block(&walk_and_run)
end

context 'dog' do
  setup do
    @object = dog
  end
  merge_block(&walk_and_run)
end

Upvotes: 3

Related Questions