Some tips on Rails unit testing

Good and well-covered unit tests prevents breaking changes and helps refactoring in the future.

In this article, i will write up some tips and thoughts about unit testing in Ruby on Rails development. I hope you find some of them helpful.

Fail fast
Fail fast is very useful when doing TDD (Test Driven Development), or when there are a bunch of failed tests need to be fixed one by one. Instead of running all your test suites, fail fast will abort once your test runner fails to pass one test suite. It saves time and let you focus on single problem.

Rails 5 has shipped fail fast feature for you, simply use `rails test -f` or `rails test --fail-fast` to enable fail fast option.

For older versions, you can try minitest-fail-fast gem. Notice that i did not check if minitest-fail-fast is still working, you can figure it out by yourself.

m: run single test by line number
If you have used RSpec, you might would miss one feature RSpec offers: run single test by line number.
In RSpec you can use:
`rspec ./spec/controllers/posts_controller_spec.rb:6` to run the test located in line 6 of `posts_controller_spec.rb`. It's a very useful when you are investigating on one specific test.

For minitest, use m to do it.

Byebug is always a good helper

I use byebug a lot nowadays, it makes investigating bugs dead simple. I used to be a 'puts' only debugger, after i did some C# programming and watched Jim Weirich's presentation Mastering the ruby debugger
<iframe width="420" height="345" src="" frameborder="0" allowfullscreen></iframe>
I decided to give debugger a try, and now i can't do without it.

You should also try pry-byebug if you prefer to use pry rather than IRB, it integrates pry and byebug, gives byebug colorful printing in terminal.

Checkups and error tracking

Ryan Laughlin's talk: The Doctor Is In: Using checkups to find bugs in production on Rails Conf 2018 is very interesting. As we know, tests can not guarantee there would be no bug in production. It's hard or impossible to test some cases under development environment, for example, race condition. In Ryan's talk, he introduced a way to detect production bugs by using scheduled tasks(checkups). Ryan also recommended using error tracking to collect errors. At my company, we use Errbit and Airbrake to collect production errors.

The video is up, check it out: video

I hope you can find some of those tips helpful. Cheers.