Reputation: 16383
From inside the spec file how do I detect if the file is being run as part of a test suite or by itself. If it is being run by itself, I want verbose output, but if it is being as one file of many, then I want to suppress the output.
For example if the file is 'spec/models/my_model_spec.rb' I want to tell the difference between
rspec spec
and
rspec spec/models/my_model_spec.rb
Upvotes: 1
Views: 524
Reputation: 3585
I found this commented out in my spec_helper.rb
file:
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
Moving it into the RSpec.configure do |config|
block produced the results you're looking for.
EDIT
RSpec supplies four different output formatters: progress, documentation, HTML, and JSON. The last two are self explanatory. The first one, progress, is the default formatter. It prints dots representing the progress within the test run. Green dots equal a successful test run.
The other formatter, documentation, uses the describe
, context
, and it
descriptions to show test results. So, given this RSpec structure:
describe Stack do
describe '#push' do
context 'when the stack is empty' do
it 'increases the size of the stack by 1'
end
context 'when the stack is full' do
it 'throws a stack overflow exception'
it 'does not increase the size of the stack'
end
end
end
The Documentation formatter would output this:
Stack
#push
when the stack is empty
increases the size of the stack by 1
when the stack is full
throws a stack overflow exception
does not increase the size of the stack
You can try out the various formatters on the command line, like this:
rspec --format progress
rspec --format doc (or documentation)
rspec --format html
rspec --format json
The configuration code in the spec_helper above allows you to change the default_formatter for situations where you are only running one file. You can always override the default formatter by specifying a different one on the command line.
The comments on the RSpec source code helped me answer this question: https://github.com/rspec/rspec-core/blob/7b6b9c3f2e2878213f97d6fc9e9eb23c323cfe1c/lib/rspec/core/formatters.rb
Upvotes: 1