Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 338
Backo Avatar asked Mar 31 '12 17:03

Backo


2 Answers

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
like image 115
apneadiving Avatar answered Oct 23 '22 16:10

apneadiving


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
like image 29
Frederick Cheung Avatar answered Oct 23 '22 17:10

Frederick Cheung