How to run only a specific set of test files in RSpec (using tags or test file pattern)?
RSpec allows running only specific test examples using --tag
option. You can also skip some of the test examples using --tag ~skip
(~
char means skip the tagged test examples).
When you use knapsack_pro
gem and you want to run only some of the tests, for instance, only feature tests with the tag :feature
, then we recommend controlling the list of test files to be run in parallel with the environment variable KNAPSACK_PRO_TEST_FILE_PATTERN
. The test file pattern supports any glob pattern handled by Dir.glob.
KNAPSACK_PRO_TEST_FILE_PATTERN="spec/features/**{,/*/**}/*_spec.rb" \
bundle exec rake knapsack_pro:queue:rspec
If you want to exclude some of the test files then we recommend using KNAPSACK_PRO_TEST_FILE_EXCLUDE_PATTERN
.
Thanks to that, knapsack_pro
does not have to load test files that are not meant to be run. If you use the RSpec --tag ~skip
option then RSpec has to load the file and then skip the test examples from it. This is pointless if you know you don't want to run any test examples from a test file.
KNAPSACK_PRO_TEST_FILE_PATTERN="spec/controllers/**{,/*/**}/*_spec.rb" \
KNAPSACK_PRO_TEST_FILE_EXCLUDE_PATTERN="spec/controllers/admin/**{,/*/**}/*_spec.rb" \
bundle exec rake knapsack_pro:queue:rspec
The only case when it might be useful to use the RSpec tag option is when you have a test file and only a few test examples contain tags and others don't. In such a case, you want to load the test file to run only a few test examples from it.
bundle exec rake "knapsack_pro:queue:rspec[--tag mytag]"
# spec/foo_spec.rb
describe 'Foo' do
# this test example will be executed because it has mytag
it 'a', :mytag do
expect(true).to be true
end
# this test example won't be executed because it has no mytag
it 'b' do
expect(true).to be true
end
end
If you run the knapsack_pro command multiple times in a single CI build, for instance, you run unit tests and feature tests as separate steps, then it's recommended to use a separate API token. Each set of tests that are run in parallel should have its API token to properly track the execution time of your test files and inform future test splits.
Related questions
- How to run a specific list of test files or only some tests from test file? - define your list of test files (file by file instead of using test file pattern)
- How to exclude tests from running them?
- How to run only RSpec feature tests or non feature tests?
- How to run tests from a specific directory (only system tests or features specs)?
- How can I run tests from multiple directories?
Dir.glob
pattern examples forKNAPSACK_PRO_TEST_FILE_PATTERN
andKNAPSACK_PRO_TEST_FILE_EXCLUDE_PATTERN