选项 1:如果这适用于您的所有测试,您可以在配置中设置它
# spec/spec_helper.rb
RSpec.configure do |config|
config.before(:all) do
puts "In #{self.class.description}"
end
config.before(:all) do
puts "More stuff can be added in chain"
end
end
选项 2:如果您只想在某些测试中使用它并且上下文会更复杂一些,您可以使用shared_context
# spec/support/some_shared_context.rb
shared_context "putting class" do
before :all do
puts "In #{self.class.description}"
end
end
# Test file
require 'spec/support/some_shared_context.rb'
describe "test foo" do
include_context "putting class"
# normal test code
end
有关 shared_context 的更多信息:https ://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-context