If you run bin/rails -h in a Rails 5 app, you will see a new command for running tests.
Before Rails 5, we had to use bin/rake test to run tests.
But in Rails 5, we can use bin/rails test.
It is not just replacement of old rake task but it is backed by a test runner
inspired from RSpec, minitest-reporters, maxitest and others.
Let’s see what bin/rails test can do.
Running a single test
Now it is possible to run a single test out of the box using the
line number of the test.
Rails will intelligently run the test from user_test.rb having line number 27.
Note that the line number 27 does not need to be first line of the test.
Below is an example.
In the above case, test_valid_user can be run as long as the line number
provided is between 22 and 30.
Running multiple tests
You can also pass multiple test paths and Rails will run all of those tests.
It is also possible to run all tests from a directory.
Improved failure messages
When a test fails, Rails displays a command which can be used to just run
the failed test.
I can simply copy
bin/rails test test/controllers/posts_controller_test.rb:15
and rerun the failing test.
By default when a test fails then rails reports about the test failures
and then moves on to the next test. If you want to stop running the test
when a test fails then use option -f.
Defer test output until the end of the full test run
By default when a test fails then rails prints F and then details
about the failure like what assertion failed and how to re run the test
If you want to have a clean output of . and F and would like all the
test failures report to come at the every end then use option -d.
Better backtrace output
By default when an error is encountered while running the test
then the output does not contain full stacktrace.
This makes debugging little bit difficult.
Now we can use -b switch,
which will display complete backtrace of error message.
Leveraging power of Minitest
The test runner also leverages power of minitest by providing some handy options.
Switch -s to provide your own seed
Now we can also provide our own seed using -s switch.
Switch -n to run matching tests
Switch -n will run tests matching
the given string or regular expression pattern.
It is also possible to see the verbose output using -v switch.
It shows time required to run each test.
This would help in detecting slow running tests.
Now by default we will get colored output.
No need to add additional gem to colored output.
With all these awesome features, testing Rails 5 apps has definitely become
a better experience.
Rails has shipped all these features within
the framework itself so you don’t have to use multiple gems and libraries to achieve
all of these things.
Share this article:
Subscribe to our monthly newsletter
Thank you! You have successfully subscribed to our newsletter.