In Rails 7.1,
developers can now run tests for a specific section of code
by passing a line range (a-b) to the
rails test command.
Before Rails 7.1
Consider a large test file with 100 tests,
and you want to run the tests from line 20 to line 30.
class MathTest < ActiveSupport::TestCase
test "sum" do
test "square_root" do
test "if_number_is_a_perfect_square" do
test "if_number_is_prime" do
Before Rails 7.1,
if you wanted to run the tests from lines 20 to 30,
you had to execute them individually by specifying the line number
passing the method name.
rails test test/math_test.rb:20
rails test test/math_test.rb:25
rails test test/math_test.rb:30
rails test test/math_test.rb -n test_square_root
rails test test/math_test.rb -n test_if_number_is_a_perfect_square
rails test test/math_test.rb -n test_if_number_is_prime
Specifying the line number or method name is useful for
running a single test case,
but it is not ideal for running multiple tests
within a given line range.
In Rails 7.1
Rails 7.1 allows running tests
for a given line range in a file.
To execute tests in a given line range,
you can use the following command:
rails test test/math_test.rb:20-30
Running 5 tests in a single process (parallelization threshold is 50)
Run options: --seed 11201
Finished in 0.010102s, 143.2322 runs/s, 143.2322 assertions/s.
5 runs, 5 assertions, 0 failures, 0 errors, 0 skips
To execute specs between two line ranges, 20-30
you need to execute the below command:
rails test test/math_test.rb:20-30:50-75
A combination of line range
a single test can be executed by passing the line range
followed by the single test line number.
rails test test/math_test.rb:20-30:50
The test command range will fail with
LoadError for the following line range.
- Negative line range
rails test test/math_test.rb:-20-30
`require': cannot load such file -- /rails/tmp/d20230906-53282-66wxlt/app/test/math_test.rb:-20-30 (LoadError)
- Not passing the line range
rails test test/math_test.rb:-30
`require': cannot load such file -- /rails/tmp/d20230906-53282-66wxlt/app/test/math_test.rb:-30 (LoadError)
rails test test/math_test.rb:20-
`require': cannot load such file -- /rails/tmp/d20230906-53282-66wxlt/app/test/math_test.rb:20- (LoadError)
To know more about this feature,
please refer to this