Is it possible to add “somewhere” a `before(:each)` hook so that all spec file can run it?

半世苍凉 提交于 2019-12-18 14:55:53

问题


I am using Ruby on Rails 3.2.2 and rspec-rails-2.8.1. In order to make my spec files DRY (Don't Repeat Yourself) and to seed the test database I would like to run a before(:each) hook for all those spec files. That is, in all my spec files I have the following code:

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

  ...
end

Is it possible to add "somewhere" that before(:each) hook so that all spec files can run it? What do you advice?


回答1:


In the spec_helper.rb:

RSpec.configure do |config|

  #your other config

  config.before(:each) do
    #your code here
  end
end

There is much configuration available. For instance: config.before(:each, :type => [:routing, :controller, :request])

You can even create your own tags and associate code to it:

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



回答2:


You can add before/after hooks in your Rspec.configure block, usually in your spec_helper:

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


来源:https://stackoverflow.com/questions/9958110/is-it-possible-to-add-somewhere-a-beforeeach-hook-so-that-all-spec-file-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!