如何制作'之前'仅限于共享示例的块?

时间:2015-01-01 10:10:33

标签: ruby rspec

请考虑以下规范test.rb

describe 'Thing' do

    shared_examples 'becomes_sad' do

            before(:all) do
                    puts 'Begin becomes_sad'
            end

            after(:all) do
                    puts 'Finalize becomes_sad'
            end

            it 'shared test #1' do; end
            it 'shared test #2' do; end

    end

    shared_examples 'becomes_happy' do

            before(:all) do
                    puts 'Begin becomes_happy'
            end

            after(:all) do
                    puts 'Finalize becomes_happy'
            end

            it 'shared test #3' do; end
    end

    include_examples 'becomes_sad'
    include_examples 'becomes_happy'

end

当我运行rspec --format documentation test.rb时,我会收到:

Thing
  Begin becomes_sad
  Begin becomes_happy
    shared test #1
    shared test #2
    shared test #3
  Finalize becomes_happy
  Finalize becomes_sad

我的期望和需要如下:

Thing
  Begin becomes_sad
    shared test #1
    shared test #2
  Finalize becomes_sad
  Begin becomes_happy
    shared test #3
  Finalize becomes_happy

我该怎么做? RSpec版本是2.99。

1 个答案:

答案 0 :(得分:1)

实际上,两个before(:all)块都将添加到同一个示例组/上下文中。因为像before钩子这样的东西作为一个整体应用于一个示例组,如果你想要不同的行为,那么你需要创建不同的示例组。

你必须按照

的方式做点什么
context 'sad' do
  include_examples 'becomes_sad'
end

context 'happy' do
  include_examples 'becomes_happy'
end