breaking into the unknown…

cleanup after rspec completion

Leave a comment

Many a time, while running rspec, our code me create some folders, files or downloaded some image or we have added some custom code to rspec, like I have started thin server in detached mode while rspec intialization in this blog. Obviously, any thing created while testing should not be persistence. It is better to cleanup things once rspec is completed. We can find detailed explanation of managing that at this link.

rspec provides after(:all) callback to manage post rspec cleanup.  We need below lines of code to do the cleanup. We can add below line of code to spec/spec_helper.rb (the best place I think)  or spec/support/your_file_name.rb or  in initialization/your_file_name.rb

RSpec.configure do |config|   #in spec_helper.rb file this line already exist, so skip to next line of code
     config.after(:all) do
          if Rails.env.test?

          Your logic will come here


One, problem I have observed with my requirement i,e stoping the server once rspec is completed is that the after(:all) callback is executed after every spec file, but I want to execute it only once when rspec run all the spec and get terminated. The solution lies in the argument we can pass to after or before callback of rspec. The available scope for these callback are as below. If we look at the default spec_helper.rb file we can find the use of these argument

:each #pass it when you want to run your logic after each test

:all  #pass it when you want to run your logic after each spec file

:suite #pass it when you want to run the callback only after completion of whole suite i,e all the spec

By the way, my complete code for stoping the server is as below. I have added it to spec_helper.rb file

config.after(:suite) do
       puts “cleaning up after rspec completion…”
       mock_server_path = File.join(Rails.root, “tmp”, “pids”, “”)
       thin_pid =
       system “kill -9 #{thin_pid}” if thin_pid
       puts “thin server stoped at 3030….”


Author: arunyadav4u

over 7 years experience in web development with Ruby on Rails.Involved in all stage of development lifecycle : requirement gathering, planing, coding, deployment & Knowledge transfer. I can adept to any situation, mixup very easily with people & can be a great friend.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s