Run RSpec tests as a Rake task

RSpec is a testing framework for Ruby. This posts show how to create a rake task that executes rspec tests. RSpec tests will be running using command ‘rake spec’.

Rake task in Rails application


If you have Rails application you can use gem ‘rspec-rails‘.

After adding to Gemfile and installing it using command

rails generate rspec:install

our project structure will be like this:

  • .rspec
  • spec/spec_helper.rb
  • spec/rails_helper.rb
  • spec/models/*_spec.rb
  • spec/features/*_spec.rb

Our tests will be located in folders inside spec/ folder. For examples, spec/features, spec/models, etc.



To run all tests use

rake spec

or run tests in a specific file:

rspec spec SPEC=spec/models/mymodel_spec.rb



Rake task without Rails


Init rspec

rspec --init

It creates files:
– .rspec
– spec/spec_helper.rb


Create your tests in spec/ folder.



Rake directives can be located either in “rakefile”, “Rakefile”, “rakefile.rb” or “Rakefile.rb” file.


require 'rake'
require 'rspec/core/rake_task' do |t|
t.pattern = Dir.glob('spec/**/*_spec.rb')
t.rspec_opts = '--format documentation'
# t.rspec_opts << ' more options'
t.rcov = true
task :default => :spec


Now we can run all tests located in spec/ folder:

rake spec


Run tests in a specific file:

rake spec SPEC=spec/features/myfeature_spec.rb



rake tasks for RSpec:


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>