Introducing Line Range Filtering in Rails 7.1 Testing

Rails 7.1 brings exciting new features to enhance our testing experience, and one of the notable additions is the support for filtering tests by line ranges.

This new syntax allows developers to easily run specific tests within a test file based on line numbers.

In this blog post, we will explore the line range filtering feature and demonstrate how it can improve our testing workflow.

Before

Before Rails 7.1, running specific tests required specifying the test method names, which could become cumbersome in large test files.

And developers could run individual test cases by appending the test’s starting line number to the test file path.

While this approach allowed for granular test execution, it was limited to running single tests at a time.

  $ rails test path/to/test_file.rb:line number

After

With line range filtering, developers can now use a more straightforward and granular approach to run only the desired tests.

The syntax for line range filtering is as follows:

  $ rails test path/to/test_file.rb:start_line-end_line

To better illustrate the usage of line range filtering, let’s consider a test file post_test.rb with the following test methods:

  require "test_helper"

  class PostTest < ActiveSupport::TestCase
    test "first" do # Line 4
      puts 'PostTest:First'
      assert true
    end

    test "second" do # Line 9
      puts 'PostTest:Second'
      assert true
    end

    test "third" do # Line 14
      puts 'PostTest:Third'
      assert true
    end

    test "fourth" do # Line 19
      puts 'PostTest:Fourth'
      assert true
    end
  end
  • Running tests from line 4 to 14:

      $ rails test test/models/post_test.rb:4-14
    
      # Output
    
      PostTest:First
      PostTest:Second
      PostTest:Third
      3 runs, 3 assertions, 0 failures, 0 errors, 0 skips
    
  • Running tests from line 4 to 9 and line 14 to 19:

      $ rails test test/models/post_test.rb:4-9:14-19
    
      # Output
    
      PostTest:First
      PostTest:Second
      PostTest:Third
      PostTest:Fourth
      4 runs, 4 assertions, 0 failures, 0 errors, 0 skips
    

Summary

The new line range filtering feature introduced in Rails 7.1 provides a convenient and efficient way to run specific tests within a test file.

By specifying the line range, developers can focus on testing specific parts of their application and streamline their testing process.

This feature enhances our testing workflow and improves developers overall testing experience.

Happy testing with Rails 7.1!

Need help on your Ruby on Rails or React project?

Join Our Newsletter