skip to content

How do you test a Rails model concern such as SoftDeletable once, and still prove every model that includes it actually works?

level: middleimportance: should knowfreq 30%

answer

  1. test behaviour through real host models
  2. shared tests in a module or shared_examples
  3. included do test ... in a Minitest concern
  4. it_behaves_like with described_class
  5. anonymous classes need a name and table

basics

~20 s

Write the concern's tests once as a shared set, a test module included into each model's test or RSpec shared_examples, and run it against every including model, so each host's table, columns and callbacks are exercised.

solid answer

~40 s

A concern has no behaviour until a host includes it, and its real risk is the contract with each host: the `deleted_at` column, scopes that combine with the model's own, callbacks in the right order. So test it through real models, written once. In Minitest, put the tests in a module that itself extends `ActiveSupport::Concern` and declares them inside `included do` with `test "..." do`, then `include SoftDeletableTests` in `DocumentTest`, `FolderTest` and `NoteTest`, each supplying the record under test through a small method. In RSpec, write `shared_examples "soft deletable"` and call `it_behaves_like "soft deletable"` in each model spec, using `described_class` or a `let` for the record. A throwaway `Class.new(ApplicationRecord)` is possible for a purely generic concern, but it needs a table and a name, since Active Model's naming raises `ArgumentError` for an anonymous class.

code

ruby · 10 lines
ruby
class FolderTest < ActiveSupport::TestCase
  include SoftDeletableTests

  def soft_deletable_record = folders(:inbox)

  test "trashing a folder keeps its documents" do
    folders(:inbox).soft_delete
    assert folders(:inbox).documents.exists?
  end
end

go deeper

for a junior

Recall that a concern is tested through models that include it, and that its tests should run for each of them.

for a middle

Show the mechanics: a test concern with included do and test blocks in Minitest, or shared_examples and it_behaves_like in RSpec, plus how each host supplies a record.

for a senior

Explain why the host contract, columns, scopes and callbacks, is what fails in production, and enforce that every including model runs the shared tests.

for a principal

Decide how far isolated dummy-class tests are worth maintaining next to host-based shared tests for concerns used across many models.

## What there is to test A concern is not callable on its own: `SoftDeletable.kept` means nothing until a model includes the module and its `included` block runs. What can break is the **contract** between the concern and each host: - the host's table must have the column the concern uses (`deleted_at`); - the concern's scopes must combine with the host's own scopes and associations; - the concern's callbacks must not fight the host's callbacks; - a method name in the concern must not clash with one the host already defines. Those are properties of the pair, so the useful tests run against **each real host**, while the test code itself is written once. ## Minitest: a shared test module Rails' `ActiveSupport::TestCase` provides the declarative `test "name" do ... end` class method. A test module that is itself a concern can declare tests inside `included do`, and they become real test methods of every test class that includes it: ```ruby # test/models/concerns/soft_deletable_tests.rb module SoftDeletableTests extend ActiveSupport::Concern included do test "soft_delete hides the record from kept" do record = soft_deletable_record record.soft_delete assert record.trashed? assert_not_includes record.class.kept, record end test "restore brings it back" do record = soft_deletable_record record.soft_delete record.restore assert_includes record.class.kept, record end end end class DocumentTest < ActiveSupport::TestCase include SoftDeletableTests def soft_deletable_record = documents(:quarterly_report) end ``` Each host test class supplies one method, here `soft_deletable_record`, returning a fixture. The same module is included in `FolderTest` and `NoteTest`, so a folder table missing `deleted_at` fails a test rather than a request. Because Concern applies the block to each test class, the test names do not collide across classes. ## RSpec: shared examples With rspec-rails the same idea uses `shared_examples`: ```ruby RSpec.shared_examples "soft deletable" do it "hides trashed records from kept" do record.soft_delete expect(described_class.kept).not_to include(record) end end RSpec.describe Document do let(:record) { create(:document) } it_behaves_like "soft deletable" end ``` `it_behaves_like` builds a nested example group, and `described_class` inside it is still `Document`, so the shared examples can call class-level scopes. `include_examples` is the variant that adds the examples to the current group instead of nesting them. ## When a dummy class is worth it For a concern that is generic and has many hosts, some teams also test it against a minimal class defined only in the test. With Active Record that means: 1. a table to point at, either an existing one through `self.table_name =` or one created in the test schema; 2. a name, because Active Model's naming raises `ArgumentError` for an anonymous class when anything asks for `model_name` (error messages, forms, polymorphic types). This tests the concern in isolation, but it does not prove any real host works, so it complements the shared tests rather than replacing them. ## Controller concerns A controller concern, for example one that adds `before_action :set_folder`, is tested the same way: through real controllers. Integration tests (`ActionDispatch::IntegrationTest`) that request a route on each controller including the concern prove the filter runs and the right folder is loaded, without poking the concern directly. A shared module of integration tests, included into each controller's test class, keeps those checks written once. ## What not to do - Testing the concern only through one model and assuming the others behave the same. - Calling private helpers of the concern directly with `send` instead of testing the public behaviour each model exposes. - Stubbing the host's columns, which hides exactly the contract failures the test should catch. - Duplicating the same assertions by hand in three model tests, which drift the moment the concern changes. A quick review check: count the models that include the concern and the test classes that include its shared tests. The numbers should match.

  • Why does `included do` work for sharing Minitest tests across test classes?
    `test "name" do` is a class method that `ActiveSupport::TestCase` gets from `ActiveSupport::Testing::Declarative`. Inside a concern's `included` block, `self` is the including test class, so each `test` call defines a test method on that class. A plain module body would run `test` on the module, which has no such method.
  • What is the difference between `it_behaves_like` and `include_examples` in RSpec?
    `it_behaves_like` wraps the shared examples in a nested example group, so `let` overrides and hooks stay scoped and the output reads "behaves like soft deletable". `include_examples` adds them straight to the current group, where two inclusions can overwrite each other's `let` definitions.

  • A concern is tested by calling SoftDeletable.kept directly in a unit test.
  • Testing the concern through one model proves every other host works too.
  • Shared tests are unnecessary because all hosts share the same concern code.
  • An anonymous Class.new(ApplicationRecord) works anywhere without a name or table.
  • Stubbing deleted_at on the host is a good way to isolate a concern's test.