dungdm93
dungdm93

Reputation: 117

pass command-line arguments to RSpec RakeTask dynamically

The rspec command comes with several options you can use to customize RSpec's behavior, including output formats, filtering examples, etc.

For example:

$ rspec path/to/spec_file.rb
$ rspec --example 'first example'
$ rspec --tag type:special
$ rspec -P "**/*_test.rb"

How can I do the same thing with rake spec (with full Rspec options).
My Rakefile:

require 'bundler/gem_tasks'
require 'rspec/core/rake_task'

task default: :spec

RSpec::Core::RakeTask.new(:spec)

I have been google but didn't find any complete answer for that. Thanks.

Upvotes: 2

Views: 1501

Answers (2)

Vitaliy Yanchuk
Vitaliy Yanchuk

Reputation: 1491

You can do it but it requires some changes. First of all you need to undefine already defined spec task if its present, then define it again. Or use other name, like spec_with_opts. Though I went through renaming.

in Rakefile

Rake::Task["spec"].clear
RSpec::Core::RakeTask.new(:spec) do |task, args|
  task.rspec_opts      = ENV['RSPEC_OPTS']            if ENV['RSPEC_OPTS'].present?
  task.pattern         = ENV['RSPEC_PATTERN']         if ENV['RSPEC_PATTERN'].present?
  task.exclude_pattern = ENV['RSPEC_EXCLUDE_PATTERN'] if ENV['RSPEC_EXCLUDE_PATTERN'].present?
end

task default: :spec

So it now can be run this way:

rake spec RSPEC_PATTERN=path/to/spec_file.rb
rake spec RSPEC_OPTS="--example 'first example'"
rake spec RSPEC_OPTS="--tag type:special"

This one wont work, you would need to use RSPEC_PATTERN

rake spec RSPEC_OPTS="-P '**/*_test.rb'" 

You can find other options that can be defined in source file: https://github.com/rspec/rspec-core/blob/master/lib/rspec/core/rake_task.rb

Upvotes: 2

max pleaner
max pleaner

Reputation: 26758

Command line arguments can be passed automatically to the ENV hash.

For example:

  • From command line: FOO=BAR rspec spec/*spec.rb
  • Inside RSpec: puts ENV["FOO"] # => "BAR"

In your Rakefile, you can use backticks to call the shell command.

Upvotes: 2

Related Questions