When testing readonly Rails models (those overriding `readonly?` to return true), creating records in tests raises `ActiveRecord::ReadOnlyRecord`. A clean solution is a `with_writable` helper that uses `class_eval` and `alias_method` to temporarily override `readonly?` to return false only within a block, then reverts it. This ensures the model behaves as readonly during actual test execution while allowing setup data to be persisted. Alternative approaches like RSpec example group helpers or raw SQL inserts are discussed but dismissed due to behavioral inconsistencies or bypassing ActiveRecord entirely.

5m read timeFrom hashrocket.com
Post cover image
Table of contents
The ProblemThe SolutionOther OptionsConclusionIf you enjoyed this post, check out these related articles next:

Sort: