| Controller Output | Expectation Type | Result |
|---|---|---|
| Array of hashes | Array of strings | ❌ Fail (structural mismatch) |
| Array of strings | Array of strings | ✅ Pass (matches your current code) |
| Form | Example | When to Use |
|---|---|---|
| New (symbol) | { status: 'ok' } |
✅ Rails default & preferred |
| Old (rocket) | { 'status' => 'ok' } |
When keys aren’t symbols (like strings or variables) |
Controller Hash → JSON → RSpec Test
| Step | Controller Code Example | JSON Output | RSpec Expectation json = JSON.parse(response.body) (*) json = JSON.parse(response.body, symbolize_names: true) |
|---|---|---|---|
| 1. Symbol keys | render json: { status: :ok, code: 200 } |
{'status':'ok','code':200} |
expect(json['status']).to eq('ok') |
| 2. String keys |
| Aspect | Benefit | Possible Drawback |
|---|---|---|
| Memory use | Fewer objects | None significant |
| Performance | Faster for literal-heavy code | Slower if code needs to mutate |
| Code safety | Prevents accidental mutation | Breaks mutation-based logic |
| Compatibility | Works fine in modern code | May break older gems |
| Predictability | Immutable by default | Surprising when global, invisible switch |
| Aspect | Effect |
|---|---|
| Performance | Slightly improved (fewer allocations). |
| Memory usage | Reduced. |
| Safety | More immutable code, fewer side effects. |
| Compatibility | Might break older gems or DSLs relying on mutable strings. |
| Rails core | Generally safe, but not guaranteed for all gems. |
| Situation | Recommended Action |
|---|---|
| Modern app with well-maintained gems | Safe to try globally (test in dev/test first). |
| Legacy code or older gems | Risky — better use the magic comment per file. |
| Gem development | Avoid setting it globally — you’ll affect consumers. |
| Rails itself | Rails 7+ core code is largely safe with frozen literals, but it doesn’t assume global freezing. |
The Six Magic Tricks
| Origin | Query (returns something) | Command (changes something) |
|---|---|---|
| Incoming | ① ✅ Assert return value | ② ✅ Assert public side effect |
| To Self | ③ 🚫 Ignore | ④ 🚫 Ignore |
| Outgoing | ⑤ 🚫 Ignore | ⑥ ✅ Mock expectation |
The Six Magic Tricks
by Sandi Metz
| Origin | Query (returns something) | Command (changes something) |
|---|---|---|
| Incoming | ① ✅ Assert return value | ② ✅ Assert public side effect |
| To Self | ③ 🚫 Ignore | ④ 🚫 Ignore |
| Outgoing | ⑤ 🚫 Ignore | ⑥ ✅ Mock expectation |
| Quality | Meaning |
|---|---|
| Thorough | Fully prove object behavior |
| Stable | Don’t break on refactors |
| Fast | Run quickly and often |
| Few | Only test what matters |
| Circus Performer | Software Developer |
|---|---|
| Risks falling mid-act | Risks breaking existing features |
| Trusts the net beneath | Trusts the test suite beneath |
| Performs with confidence | Deploys with confidence |