是否可以在`somewhere’中添加`before(:each)`钩子,以便所有spec文件都可以运行它?

我正在使用Ruby on Rails 3.2.2和rspec-rails-2.8.1。 为了使我的spec文件DRY (不要重复自己)并为test数据库播种,我想为所有这些spec文件运行一个before(:each)钩子。 也就是说,在我的所有spec文件中,我有以下代码:

 describe 'test description' do before(:each) do load "#{Rails.root}/db/seeds.rb" end ... end 

是否可以添加“somewhere” before(:each)挂钩,以便所有spec文件都可以运行它? 你有什么建议?

spec_helper.rb

 RSpec.configure do |config| #your other config config.before(:each) do #your code here end end 

有很多配置可用。 例如: config.before(:each, :type => [:routing, :controller, :request])

您甚至可以创建自己的标签并将代码与其关联:

 config.around :each, unobstrusive: true do |example| Capybara.current_driver = :rack_test example.run Capybara.current_driver = :selenium end 

您可以在Rspec.configure块中添加挂钩之前/之后,通常在spec_helper中:

 RSpec.configure do |config| config.before(:each) do ... end end