RSpec (Rails) Best Practices

Someth Victory
2 min readJul 20, 2018

--

If you google RSpec best practices, you will see so many links by many other good developers already. In this post, I just include a few additional things I found it’s cleaner and improve the readabilities. The last point of the article also suggested some other resources we should use when working with RSpec as well.

Use shoulda-matchers to improve readabilities

shoulda-matchers is a third party gem built by Thoughtbot. With shoulda-matchers, the code is very clean and easy to understand.

it { is_expected.to validate_presence_of(:name)  }
it { is_expected.to belong_to(:color) }

Group similar test in one describe group

Similar specs should be grouped under the same describe block.

Use context to describe the logic of the tested methods

Some methods contain some logics inside, the logics should be grouped in the context.

Given the #should_be_recycled? returns true when the robot’s statuses include rusty and loose_screws .

For example:

robot.rb

robot_spec.rb

Always specify test type(Rails)

Type metadata is required in RSpec Rails while, however, not providing it does not cause any issue for most cases. For best practices, the type metadata should always be provided, so that RSpec Rails understand what type of spec we are running and, most likely, this is very useful when we want to use the DSL methods.

See controller spec below:

RSpec.describe RobotsController, type: :controller do
it 'responses success' do
get :index

expect(response).to be_success
end
end

RSpec Rails understands the get method when specifying the type: controller in the metadata.

Use DSL for feature specs

I always use Capybara DSL when working with feature specs. It provides more readabilities and familiarities.

Other useful resources

There are also other third-party gems we can or should use when working with RSpec as well. See below:

Database Cleaner: To clean up the test data.

FactoryBot: To create test objects.

FFaker: To generate fake data.

Fuubar: To format the output of the specs.

RSpec Retry: To retry to failing specs in some cases where you got random error/failing specs.

VCR: To cache the response when working with third party APIs.

Capybara and Capybara Webkit: If you are writing the feature specs.

That’s it!

If you enjoy reading this article, give it a clap!

--

--

Someth Victory

I'm a cook, a father of a daughter, a dota player, a photographer, and an experienced Ruby on Rails and Javascript developer.