在测试许多状态时干掉上下文和主题重复

时间:2014-05-15 04:55:12

标签: ruby-on-rails rspec

我终于冒险尝试了,经过多年的自动化测试,我学习了RSpec。

我正在测试具有18种可能状态组合的模型。目前,我的规范看起来像这个简化示例(请注意create来自factory_girl):

describe MyModel do
  context 'in unapproved state' do
    context 'with guest account' do
      subject { build_stubbed(:my_model, :unapproved, :guest) }

      describe '#method_a' do
        it { ... }
      end

      describe '#method_b' do
        it { ... }
      end
    end

    context 'with full account' do
      subject { build_stubbed(:my_model, :unapproved, :full) }

      describe '#method_a' do
        it { ... }
      end

      describe '#method_b' do
        it { ... }
      end
    end
  end

  context 'in approved state' do
    context 'with guest account' do
      subject { build_stubbed(:my_model, :approved, :guest) }

      describe '#method_a' do
        it { ... }
      end

      describe '#method_b' do
        it { ... }
      end
    end

    context 'with full account' do
      subject { build_stubbed(:my_model, :approved, :full) }

      describe '#method_a' do
        it { ... }
      end

      describe '#method_b' do
        it { ... }
      end
    end
  end
end

这很有效,我(大多数时候)对它很满意。但是,我已经对RSpec最佳实践进行了大量阅读,并且我应该将所有describe放在最外层并将context嵌入其中(与之相反)我上面有。)

describe置于最外层对我来说非常有意义,因为它将您班级的组成部分(您实际测试的内容)组合在一起。我上面的例子将成为:

describe MyModel do
  describe '#method_a' do
    context 'in unapproved state' do
      context 'with guest account' do
        subject { build_stubbed(:my_model, :unapproved, :guest) }
        it { ... }
      end

      context 'with full account' do
        subject { build_stubbed(:my_model, :unapproved, :full) }
        it { ... }
      end
    end

    context 'in approved state' do
      context 'with guest account' do
        subject { build_stubbed(:my_model, :approved, :guest) }
        it { ... }
      end

      context 'with full account' do
        subject { build_stubbed(:my_model, :approved, :full) }
        it { ... }
      end
    end
  end

  describe '#method_a' do
    context 'in unapproved state' do
      context 'with guest account' do
        subject { build_stubbed(:my_model, :unapproved, :guest) }
        it { ... }
      end

      context 'with full account' do
        subject { build_stubbed(:my_model, :unapproved, :full) }
        it { ... }
      end
    end

    context 'in approved state' do
      context 'with guest account' do
        subject { build_stubbed(:my_model, :approved, :guest) }
        it { ... }
      end

      context 'with full account' do
        subject { build_stubbed(:my_model, :approved, :full) }
        it { ... }
      end
    end
  end
end

这很酷,我认为它使我的规范更容易阅读和导航。然而,现在有很多重复与上下文和主题。

在这种情况下减少重复的好方法是什么?

0 个答案:

没有答案