Skip to main content
Rails Engineering

Publish, review, and manage your writing.

#rails #testing #api

Testing Rails Features Through Their Public Behavior

H
Hung
• • 2 mins read
Technical article hero

Choose a behavior worth protecting

Useful tests explain what the application promises: an author can create a draft, another author cannot edit it, and readers only see approved posts. Request tests exercise routing, authentication, controller behavior, and database changes together. Model tests are useful for focused validation and state transitions.

test "anonymous readers cannot see a draft" do
  post = posts(:draft)
  get post_url(post)
  assert_response :not_found
end

This Minitest example requires a draft fixture and a show action whose public visibility policy returns 404 for that record. The expected response should match the application's chosen policy; authenticated owners may have a separate preview route.

Assert outcomes, not implementation details

When creating a post, assert that one record was saved, its owner is the signed-in user, and its initial state is draft. Submit a forged user_id and verify ownership cannot change. Avoid asserting the exact internal method sequence when a refactor could preserve all user-visible behavior.

Control external work

Use the test queue adapter to inspect enqueued jobs. Stub provider clients at their application boundary so normal tests do not send email or spend money on AI requests. Keep a separate, explicitly run integration check for provider compatibility.

Cover the edges

Include blank input, unauthorized access, withdrawn publication, and transient service failures. Use time helpers when testing expiry, and avoid random fixture dates. A small deterministic suite that catches permission leaks and broken workflows is more valuable than many assertions that merely repeat the implementation.

Share this article
Author

Hung

Reactions

React Hover to preview

Comments

This comment is hidden because the account is restricted.

TI

Tienbob

Biết gì mà nói ?

React Hover to preview

Sign in to join the conversation.

Recommended Reading