Andrea Casarin

Andrea Casarin

Published on: 12/23/2021, 7:00:00 AM - Reading time: 1 minute

Switching from Minitest to RSpec

Minitest is great and it now the standard tool to test a Ruby on Rails application, I have been using it for a long time and it works great. However while working on a client's project I found that RSpec tests are easier to read and its ecosystem provides a faster and cleaner way to write tests.

Said that I decided to switch the test suite for an application I was working on to RSpec, to try and learn this different tool. I also opted in for shoulda_matchers and factory_bot which seems to be the de-facto standard.

Here are a few hints if you want to follow the same path.

One assertion per test.

That's it, write multiple tests with one assertion each, seems unpractical at firsts but it really helps in the long run.

Prefer is_expected/expects over should.

Pretty straightforward, as per documentation now is_expected is the preferred syntax.

Use subject for main testing object.

You are supposed to define a subject which serve as main test object, then expect something from it.

Use let for other objects.

With let you can define other objects which will be edge loaded for each test as they are used. If you need that object before explicitly calling it you can use let! instead.

When using callbacks after(:save) remember to save.

This one is for factory_bot actually: you'll find yourself using callbacks to define associated object in a one-to-many or many-to-many relationship. I these cases make sure to save the object in the callback too.

Use allow_value() to test custom validations.

Now on with shoulda_matchers, which has a lot of cool ways to test model validations, however if you want to test some custom ones you can simply use allow_value and test for true or false.

Remember eq() tests equality, be() tests identity.

That's easy, but often overlooked, make sure you are testing for the right thing.

Backtrace to get context.

You can add `--backtrace` to your tests to have some clue on why they are failing.