16 May
Shared examples with Minitest - Rails Tricks Issue 7
Hi, this week I will show how you can achieve a similar behavior to Rspec’s shared examples with Minitest. We will dry the minitest tests by extracting the common parts into modules.
Imagine you generated two scaffolds, one for a “User” object and one for an “Article” object. Your scaffold tests have almost the same code for most CRUD methods, so let’s share them between the tests. To achieve this, we will create a module:
This module uses ActiveSupport::Concern to have a friendlier interface to call methods when this module is included. At that point, we will create a test for displaying the edit page of the CRUD. Instead of naming the instance variable after the actual object, we will use a generic name @subject, and to generate the URL, we will use the url_for helper with the controller generated from the @subject’s class. We need to change both of our controller tests to set the instance variable and to include this module to test the edit endpoint:
We can remove the generated tests for this edit action from each file and run the tests. To dry our tests further, let’s extract the test for deleting, showing, and listing the records and for the new record action:
Extracting the create and update tests are more involving because there are different attributes for each model, but with the help of other instance variables we can extract those too:
I hope the above examples help to extract common parts of your minitest tests into shared examples.