spec使用不同的配置运行相同的测试集

时间:2016-04-24 22:41:00

标签: ruby unit-testing testing rspec

假设一个包含许多测试的spec文件:

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

我想做同样的一组测试,但是使用不同的配置,例如,在before(:all)之前,它看起来像这样:

before(:all) do
   @object = buildObjectB
end

这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:0)

我认为你想要使用context。就像describe一样,但它有更多的语义名称,更适合像你这样的情况。

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

如果您的测试失败,它会链接所有describecontextit参数,并为您提供测试示例的完整说明。

答案 1 :(得分:0)

您可以使用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

(假设两个对象的测试都相同)