RSpec--Hooks钩子的定义和执行

1. rspec钩子

  • Module RSpec::Core::Hooks
  • 实例方法:before(scope, conditions, &block):scope [Symbol]类型表示被作用的对象(:example/:each, :context/:all, :suite),conditions [Hash]类型表示被作用的对象应满足的条件
before(:suite)         # Declared in RSpec.configure, 在所有 *_spec 文件之前执行一次
after(:suite)          # Declared in RSpec.configure, 在所有 *_spec 文件之后执行一次

before(:context)       # Declared in RSpec.configure,或者是某个spec.rb文件的describe/context块中
after(:context)        # Declared in RSpec.configure,或者是某个spec.rb文件的describe/context块中

before(:example)       # Declared in RSpec.configure,或者是某个spec.rb文件的describe/context块中
after(:example)        # Declared in RSpec.configure,或者是某个spec.rb文件的describe/context块中
  • 实例:
describe 'Test' do
  # 默认对所有的example有效
  before(:example) do
    puts "before all examples"
  end
  
  # 只对it中指定了 color: 'green' 的有效
  before(:example, :color=>'green') do
    puts "before example with color green"
  end

  context 'cases' do
    it 'case1', color: 'green' do
    # 会输出两条语句
    end

    it 'case2', color: 'red' do
    # 只会输出第一条语句
    end
  end
end

2. 调用钩子的对象

# spec_helper.rb
RSpec.configure do |config|
  puts self         # main

  config.before(:suite) do
    puts self       #
  end
  
  # 在某个*_spec文件执行之前执行,例如test_spec.rb,test2_spec.rb
  config.before(:context) do
    puts self      # #,#
  end

  config.before(:example) do
    puts self    # #, #
  end
end


# test_spec.rb
describe 'Test' do
  puts self      #  RSpec::ExampleGroups::Test

  before(:context) do
    puts self    # #
  end

  before(:example) do
    puts self   # #, #
  end
  

  context 'Cases' do
    puts self    # RSpec::ExampleGroups::Test::Cases
    it 'cases1' do
    end
  end

  it 'case2' do
  end
end

你可能感兴趣的:(RSpec--Hooks钩子的定义和执行)