Testing Rails Features Through Their Public Behavior
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.
Hung
Cảm xúc
Bình luận
Bình luận này bị ẩn vì tài khoản đang bị hạn chế.
Tienbob
Biết gì mà nói ?
Đăng nhập để tham gia cuộc trò chuyện.