Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
If you're developing an app with Ruby on Rails, you're probably already familiar with RSpec testing. But every time you open the spec_helper.rb and rails_helper.rb files, you can think: why are there two of them and how are they different?
spec_helper.rb: base/ground for testing
This file is the basic configuration for RSpec. Its task — is to provide minimal settings for tests. Ideally, spec_helper.rb should not depend on Rails. If simple - this is a file that contains basic settings for RSpec, namely:
- Visualization of tests: you can ask how the test results will look in the console (for example, progress bar).
- Connecting additional utilities: special libraries such as Faker, FactoryBot or custom test helpers can be imported into the file.
- Debugging: enable detailed log mode or integrate with pry for debugging during testing.
This file is useful if you need to test individual Ruby classes or methods that independent of Rails. Use only spec_helper.rb allows you to run tests faster because Rails does not boot.
rails_helper.rb: integration with Rails
rails_helper.rb based on spec_helper.rb, but adds Rails-specific settings. Among them:
- automatic Rails loading;
- integration with ActiveRecord to work with the database in tests;
- connection of auxiliary modules for testing controllers, models and pins.
This file is often used for tests that depend on Rails functionality. For example, testing models with validations or controllers with database queries requires loading rails_helper.rb.
What and when to connect?
- Use spec_helper.rbwhen you test logic that is not related to Rails. These can be regular Ruby classes, PORO or auxiliary modules.
- Use rails_helper.rbwhen your tests depend on the Rails environment.
In large projects, it is important to minimize the load on the test process (speed up tests on CI, and reduce the check for the use of resources). If you always use rails_helper.rb, even for simple tests, the test run time increases. On the other hand, too frequent separation can make adjustment difficult. Therefore, it is worth combining flexibility and performance, choosing carefully between these files depending on the tasks.
This post doesn't have any additions from the author yet.