如何使 'before' 块仅特定于共享示例?

How to make 'before' blocks specific to shared examples only?

考虑以下规范 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。

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

你必须按照

做一些事情
context 'sad' do
  include_examples 'becomes_sad'
end

context 'happy' do
  include_examples 'becomes_happy'
end