This was the tip of the week in the July 8, 2021 Ruby Weekly Newsletter.


Sometimes when writing Ruby tests with RSpec we want to run the whole test suite. Other times, we want to run only specific tests. Here are a few different ways to only run part of a test suite:

–fail-fast flag

Running a spec file or full test suite with the --fail-fast flag will stop the tests at the first failure. For example: rspec spec --fail-fast will complete fully only if there are no failures in the suite. This can be helpful for large suites.

–example (-e) flag

The --example (or -e) flag takes a string argument and runs only examples whose names include the argument.

For example, if we had this spec file spec/example_spec.rb:

RSpec.describe Example do
  it "runs this specific test" do
    ...
  end

  it "does not run this" do
    ...
  end
end

We can run rspec spec/example_spec.rb -e "specific test" and only the first test will run. This is an additional reason it can be helpful to have well described tests.

: flag

We can run an example on a specific line by including that line number right after the specific file when running the test. We can add line numbers to our previous example to clarify:

1 RSpec.describe Example do
2   it "runs this specific test" do
3     ...
4   end
5 
6   it "does not run this" do
7     ...
8   end
9 end

We can run rspec spec/example_spec.rb:2 to only run the first spec.

:focus

If we only want to run a specific context or example, we can add the following to our spec/spec_helper.rb to configure the ability to focus on a specific set of tests:

RSpec.configure do |config|
  config.filter_run focus: true
end

and then pass the symbol :focus as an optional argument to our example or group before running our tests:

describe "only testing this", :focus do
  ...
end

Hopefully some of these methods of running specific tests are useful in avoiding running the full suite unnecessarily!