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

rspec-rails

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

After adding to Gemfile and installing it using command

[codesyntax lang=”bash”]

rails generate rspec:install

[/codesyntax]

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.

 

rake

To run all tests use
[codesyntax lang=”bash”]
rake spec
[/codesyntax]

or run tests in a specific file:

[codesyntax lang=”bash”]

rspec spec SPEC=spec/models/mymodel_spec.rb

[/codesyntax]

 

 

Rake task without Rails

 

Init rspec
[codesyntax lang=”rails”]
rspec –init
[/codesyntax]
It creates files:
– .rspec
– spec/spec_helper.rb

 

Create your tests in spec/ folder.

 

Rakefile

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

Rakefile:

[codesyntax lang=”rails”]

require ‘rake’
require ‘rspec/core/rake_task’

 

RSpec::Core::RakeTask.new(:spec) do |t|

t.pattern = Dir.glob(‘spec/**/*_spec.rb’)

t.rspec_opts = ‘–format documentation’

# t.rspec_opts << ‘ more options’
t.rcov = true
end

task :default => :spec
[/codesyntax]

 

Now we can run all tests located in spec/ folder:
[codesyntax lang=”bash”]
rake spec
[/codesyntax]

 

Run tests in a specific file:

[codesyntax lang=”bash”]

rake spec SPEC=spec/features/myfeature_spec.rb

[/codesyntax]

 

Links

rake tasks for RSpec:

https://www.relishapp.com/rspec/rspec-core/docs/command-line/rake-task

 

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>