---
title: "Testing Readonly Models"
url: https://daily.dev/posts/testing-readonly-models-0i7apxofd
source_url: https://hashrocket.com/blog/posts/testing-readonly-models
type: article
source: "Hashrocket"
published: 2026-03-17T13:26:22.885Z
updated: 2026-03-17T13:26:46.893Z
tags: ["testing", "ruby", "rails"]
reading_time: 5
upvotes: 1
comments: 0
language: en
---

> ## Documentation Index
> Fetch the complete documentation index at: https://daily.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Testing Readonly Models

**[Hashrocket](https://daily.dev/sources/hashrocket)** · 5 min read · 1 upvotes · 0 comments

## Summary

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.

## Full article

daily.dev links to this article rather than hosting it. Read it at the original source: <https://hashrocket.com/blog/posts/testing-readonly-models>

## Similar posts on daily.dev

- [Rewrite with Confidence: Validating Business Rules Through Isolated Testing](https://daily.dev/posts/rewrite-with-confidence-validating-business-rules-through-isolated-testing-dhprnbw12) · arkency · 0 upvotes · 0 comments
- [Painfully Simple Test Case Mistakes That Are Easy to Fix - FastRuby.io](https://daily.dev/posts/painfully-simple-test-case-mistakes-that-are-easy-to-fix---fastruby-io-qjqh0s0e4) · RUBYLAND · 0 upvotes · 0 comments
- [Wise Testing: What to Test \(and Ignore\) as a Solo Rails Developer](https://daily.dev/posts/wise-testing-what-to-test-and-ignore-as-a-solo-rails-developer-r9boy5cm4) · Ruby Flow · 3 upvotes · 0 comments

---

Tags: [#testing](https://daily.dev/tags/testing), [#ruby](https://daily.dev/tags/ruby), [#rails](https://daily.dev/tags/rails)

[View this post on daily.dev](https://daily.dev/posts/testing-readonly-models-0i7apxofd)
