Ruby on Rails interview questions with worked answers
A strong Rails answer traces a request from authenticated identity through a scoped relation, permitted input, database constraint and persisted result. Explain when a relation actually queries, what a transaction includes, which side effects occur after commit, and what happens if a job or callback is repeated. Rails conventions make common paths concise; they do not replace authorization policy, database constraints or verification against the configured adapter.
For: Mid-level to senior Rails application engineers
Guide scope and versions
Rails 8.1 application behavior. SQL examples target PostgreSQL 16; job and transaction guarantees depend on the named adapter.
Question 1 of 12
A customer changes an invoice ID in the URL. How do you keep the lookup inside their account?
Start from an account the authenticated user is allowed to act for, then retrieve the invoice through that account's relation. A globally scoped Invoice.find(params[:id]) only proves that an invoice exists. A nested lookup such as @account.invoices.find(params[:id]) also enforces the account boundary in the query, assuming @account itself was established by trusted authorization code.
Treat URL identifiers, hidden form fields and submitted account IDs as selectors, not evidence of permission. The account context should come from the authenticated principal and the application's membership or policy check. Once established, keep every record lookup and mutation under that scope: the initial show action, update action, nested association lookup, and any later download or status route that the product actually implements. Returning 404 for a resource outside the caller's scope can avoid disclosing its existence, while a policy may choose 403; use one deliberate response rule and test it consistently.
Associations help form the SQL boundary, but they do not create authorization by themselves. An association can be misconfigured, an unscoped escape hatch can bypass it, and a cached object can be passed from another path. Inspect the generated relation and the authenticated account-selection rule. A useful test creates two accounts with similar records, signs in a user for one, requests the other's record ID, and asserts both the chosen response and that no foreign record data is rendered or changed.
Ruby on Rails 8.1 · Worked example
class InvoicesController < ApplicationController
def show
@account = current_user.accounts.find(params[:account_id])
@invoice = @account.invoices.find(params[:id])
end
def update
@account = current_user.accounts.find(params[:account_id])
@invoice = @account.invoices.find(params[:id])
@invoice.update!(invoice_params)
redirect_to [@account, @invoice]
end
private
def invoice_params
params.require(:invoice).permit(:memo)
end
end
Assuming the application defines current_user and a real membership association, the lookup can return only an invoice belonging to one of that user's accounts. An invoice ID from another account raises ActiveRecord::RecordNotFound and cannot be updated through this path. The example permits only memo; that field whitelist is not the authorization check.
Executed with Rails 8.1.4 and Ruby 3.4.12 against a disposable synthetic PostgreSQL 16 database; all 12 tests passed.
Follow-up: Should every out-of-scope invoice lookup return 403?
Not necessarily. The application can consistently return 404 to avoid revealing whether another account's invoice exists, or return 403 when disclosure is acceptable and policy calls for it. The key is that the database lookup and response do not leak the record, and tests cover the selected behavior.
What security guarantee do strong parameters provide, and what do they leave to the application?
Strong parameters restrict which submitted keys can be used for mass assignment. They do not authenticate the caller, decide which records the caller may access, validate business rules, or prevent a permitted value from being malicious. Treat parameter filtering as one input boundary and perform authorization and domain validation separately.
A form can submit fields that are absent from the visible controls, including admin, account_id, status or ownership attributes. Requiring a nested parameter and permitting only fields the user is allowed to edit prevents accidental mass assignment of everything in the request. It does not make the allowed memo safe in every context, and it does not make a submitted object ID trustworthy. Build the record lookup from authorized state first, then apply a narrow parameter list to that object.
Strong Parameters also are not a complete validation layer. A permitted value can violate a domain invariant, exceed a business limit, or be inconsistent with the current record state. Model validations can provide user-facing errors, while database constraints enforce invariants against concurrent writers and alternate write paths. Separate these responsibilities in code and in tests so a change to a parameter list cannot silently grant access or weaken persistence guarantees.
Ruby on Rails 8.1 · Worked example
def update
@project = current_user.projects.find(params[:id])
@project.update!(project_params)
end
private
def project_params
params.require(:project).permit(:name, :summary)
end
A request that also submits owner_id or billing_tier does not mass-assign those fields through this method. The scoped lookup independently ensures the project belongs to the current user. If users may edit projects through a separate role or policy, that decision belongs in that policy, not in the permitted-key list.
Executed with Rails 8.1.4 and Ruby 3.4.12 against a disposable synthetic PostgreSQL 16 database; all 12 tests passed.
Follow-up: Can a permitted :status field safely let a customer mark an invoice paid?
Only if the product explicitly grants that transition and the application validates the current state and caller's authority. Usually payment status is set by a trusted payment workflow, not copied from customer parameters. A key allowlist cannot express the complete state-transition policy.
When does an Active Record relation run SQL, and why can a console appear to run it early?
Most relation-building calls such as where, order and limit return a lazy ActiveRecord::Relation; they describe a query without immediately loading its rows. SQL runs when code asks for the records or a calculation, for example with each, to_a, first or count. The Rails console inspects the returned value for display, which can load it and make a relation look eager.
A relation is not the result array. It can be further composed, passed to another method, or reused before evaluation. That is useful for building scopes and adding conditions at the boundary, but it can also hide database work inside presentation or helper code. Calling an aggregate such as count can issue a SQL calculation without loading records; materializing with to_a instantiates objects. Calling both may perform separate operations, depending on whether the relation is already loaded and which methods are used.
When a request seems to issue duplicate queries, locate the evaluation points and inspect SQL logs or query instrumentation instead of assuming that where executed. Reusing a relation does not guarantee one cached snapshot across repeated database evaluation. If the underlying rows change between evaluations, separate queries may observe different committed state under the database's isolation level. Decide whether the code needs a loaded snapshot, one aggregate, or a transaction with defined consistency, and test that behavior against the configured adapter.
Ruby on Rails 8.1 with PostgreSQL 16 · Worked example
scope = Invoice.where(account_id: 42, state: "open").order(:id)
# No rows have been requested yet.
count = scope.count
rows = scope.to_a
The count call sends a SELECT COUNT(*) calculation to PostgreSQL and sets count to the matching row count. to_a then requests and loads the matching invoice rows into an array; it is a second database operation, not a conversion of the prior count into records. If the rows change between those statements, the values can differ.
Executed with Rails 8.1.4 and Ruby 3.4.12 against a disposable synthetic PostgreSQL 16 database; all 12 tests passed.
Follow-up: Does assigning scope = Invoice.where(account_id: 42) freeze the records at that line?
No. It captures a relation definition. The query executes later, and later query evaluation can observe current database state. If a consistent multi-query view matters, choose and verify an explicit transaction/isolation boundary rather than relying on a Ruby variable.
A page renders ten invoices and then loads each account separately. How would you remove the N+1 queries?
Load the association along with the parent records when the view will use it, then check the actual query count and memory cost. Rails offers preload, includes and eager_load, which use different query strategies. strict_loading can turn an unexpected lazy association load into a test or development failure instead of letting an N+1 pattern hide in a template.
If a page loads ten invoices and then calls invoice.account.name for each one, it can issue one invoice query plus ten account queries. preload(:account) makes the parent query and one IN (...) association query, which is often straightforward. eager_load(:account) joins the association in one SQL statement; that can multiply result rows for collection associations and produce a larger transfer. includes can choose separate queries or a join depending on how the relation references the included table, so its exact SQL is not always obvious from the method name.
Fewer round trips do not automatically mean lower resource use. Preloading a large collection can instantiate many objects, and selecting only columns must preserve keys needed to connect associations. Measure representative page size and query count. Use strict_loading on an appropriate relation or association to catch accidental loads, while recognizing that it is a guardrail rather than an authorization boundary or a substitute for query-plan review.
Ruby on Rails 8.1 · Worked example
invoices = account.invoices.preload(:customer).strict_loading
invoices.each do |invoice|
puts invoice.customer.name
end
For ten invoices with ten distinct customers, the un-preloaded pattern can issue eleven queries: one invoice query and one customer query per invoice. With preload, Rails issues a query for the invoices and one query for the referenced customers, so this example uses two data queries. If a view accesses an association that was not loaded, strict loading raises ActiveRecord::StrictLoadingViolationError instead of silently issuing another query.
Executed with Rails 8.1.4 and Ruby 3.4.12 against a disposable synthetic PostgreSQL 16 database; all 12 tests passed.
Follow-up: Would you always replace preload with a join to get one SQL statement?
No. A join can duplicate parent columns across many child rows and complicate pagination or aggregates. Choose based on the relation, result shape and query plan, then measure it. preload often gives predictable separate queries; eager_load explicitly requests a left outer join.
A nightly task processes a large table. Why can `Model.all.each` exhaust memory, and what does batching change?
Model.all.each can load and retain every matching Active Record object in one array. Batch APIs such as find_each fetch a bounded group of records at a time and yield them incrementally. Batching bounds the collection held by Active Record, but it does not bound memory retained by the job's own arrays, associations, serialized output or accumulated errors.
A relation can look lightweight until an iterator requires its records. Calling to_a or traversing the whole relation may instantiate the full result set. find_each and find_in_batches are designed for work that should not load the entire table at once. Use an explicit batch size based on object size and work per row, and make ordering and cursor assumptions visible. Current rows can be inserted or updated while the task runs, so define whether the job processes a moving set or a fixed cutoff and make reruns safe.
The batch loop is only one part of the memory model. A job that stores every processed ID, keeps association graphs alive, or builds one giant CSV string still grows with the total workload. Prefer bounded transformations and incremental output or durable checkpoints if the use case requires them. For concurrent writes, the query's ordering and cursor columns must be stable enough for the selected batch strategy; test boundary changes and document whether late-arriving rows belong to this run.
Ruby on Rails 8.1 with PostgreSQL 16 · Worked example
cutoff = Time.current
Invoice.where("created_at < ?", cutoff).find_each(batch_size: 500) do |invoice|
ExportOneInvoice.call(invoice)
end
The task captures one cutoff instant, then asks Rails to fetch and yield batches of up to 500 matching invoices. It does not build one array containing every invoice. The timestamp predicate excludes rows whose stored created_at is at or after the cutoff; it does not define a fixed set of rows visible throughout the run. A row inserted later with a backdated or preassigned created_at before the cutoff can appear in a later batch, while updates and deletes can also change what later batches see. ExportOneInvoice must also avoid accumulating unbounded state.
Executed with Rails 8.1.4 and Ruby 3.4.12 against a disposable synthetic PostgreSQL 16 database; all 12 tests passed.
Follow-up: Does find_each guarantee the exact same set of rows on every retry?
No. It batches query work; it does not create a durable snapshot or idempotency protocol. Define the run's membership boundary, make each item's effect repeat-safe or checkpointed, and choose a transaction strategy only if the database and workload can sustain it.
Two requests create the same account slug at once. Why is a uniqueness validation not enough?
A Rails uniqueness validation performs a query before saving, so two concurrent requests can both observe that the value is unused. A unique index in the database is the concurrency-safe authority that allows at most one conflicting insert to commit. Keep the model validation for a friendly error path, and handle the database conflict as a possible result of concurrent writes.
The race is a time-of-check/time-of-use problem: request A checks, request B checks, then both attempt the insert. Each model instance can be valid when checked even though their combined writes violate the invariant. On PostgreSQL 16, a unique index or constraint arbitrates the conflicting writes; one succeeds and the other receives a unique-violation error that Rails surfaces as ActiveRecord::RecordNotUnique in the common adapter path. A composite invariant such as one non-null slug per account needs a unique index over both columns, matching the validation's scope, and both columns must also be NOT NULL if nulls are not valid values.
The validation and database constraint serve different users. The validation can return a predictable validation error before the common conflict reaches the database. The index protects all writers, including jobs, scripts and other services. If code catches a PostgreSQL constraint error inside a transaction, that transaction is aborted until rolled back; do not rescue and continue issuing SQL in the same failed transaction. Translate the conflict at an outer boundary or use a database operation with explicit conflict semantics, then verify the exact Rails adapter exception behavior.
Ruby on Rails 8.1 with PostgreSQL 16 · Worked example
class Account < ApplicationRecord
validates :slug, uniqueness: { scope: :organization_id }
end
class AddUniqueOrganizationSlug < ActiveRecord::Migration[8.1]
def change
change_column_null :accounts, :organization_id, false
change_column_null :accounts, :slug, false
add_index :accounts, [:organization_id, :slug], unique: true
end
end
If two concurrent transactions try to insert the same non-null (organization_id, slug) pair, both validations may pass, but PostgreSQL's unique index allows only one row to commit. The losing insert raises a uniqueness conflict rather than creating a duplicate. The NOT NULL changes are part of the invariant: PostgreSQL's default unique-index semantics allow multiple rows when indexed values include NULL. Existing null rows must be handled before those changes can be applied. The migration shown defines the durable pairwise rule; a production migration on a large live table would need an appropriate rollout plan, which is outside this example.
Executed with Rails 8.1.4 and Ruby 3.4.12 against a disposable synthetic PostgreSQL 16 database; all 12 tests passed.
Follow-up: Should the losing request always become a server error?
No. The application can catch the conflict outside the failed transaction, reload the competing value or add a validation error, and return its normal conflict response. Keep the database as the final guard and ensure the response does not claim the attempted insert succeeded.
An invoice update writes three rows and sends a message. What does an Active Record transaction cover?
An Active Record transaction groups database operations on the same database connection into one commit or rollback boundary. It can make the invoice, line-item and ledger writes atomic when they participate in that connection's transaction. It does not roll back an email, HTTP request, filesystem write, or a write on another database connection.
Put related database changes in the smallest transaction that preserves the business invariant. If an exception escapes the block, Rails rolls back the transaction and re-raises it; ActiveRecord::Rollback is a special exception Rails rolls back and suppresses at the transaction boundary. Nested transaction blocks generally join the existing transaction, so a nested rollback may not independently undo just the inner work. requires_new: true asks Rails for a savepoint on adapters that support it, not a separate durable commit visible outside the outer transaction.
Do not hold a database transaction open while calling a slow external service. The service can accept the request and the database can later roll back, or the database can commit and the remote call can fail. A transaction on one connection also cannot promise atomicity across a second database configured through Rails multiple databases. If a process needs a durable cross-system event, record intent in the same database transaction and design independent delivery and idempotent handling.
Ruby on Rails 8.1 with PostgreSQL 16 · Worked example
Invoice.transaction do
invoice.update!(status: "issued")
invoice.line_items.each { |item| LedgerEntry.create!(invoice: invoice, amount: item.total) }
end
If the third ledger insert raises before the block finishes, PostgreSQL rolls back the invoice status change and prior ledger inserts in this transaction. No email or API call is included here. The example assumes these Active Record writes use the same connection and database; writes through another database configuration are not covered by this transaction.
Executed with Rails 8.1.4 and Ruby 3.4.12 against a disposable synthetic PostgreSQL 16 database; all 12 tests passed.
Follow-up: Can ActiveRecord::Rollback signal the controller that the transaction failed?
Not by itself. Rails rolls back and swallows that exception at the transaction boundary. Return an explicit result or raise a different exception if the caller must distinguish failure; otherwise code after the block can run as if control returned normally.
A job must run only after an order is committed. What does `after_commit` guarantee, and what gap remains?
An after_commit callback runs after the database transaction commits, so the callback does not enqueue work for data that later rolls back. Rails 8.1 also documents deferring Active Job enqueueing until transaction commit. Neither mechanism by itself guarantees that enqueueing and the database commit are one atomic event: the process can fail after commit but before the queue accepts the job.
A callback that sends a message in after_save can run before the outer transaction commits; a later rollback would leave an external side effect for a row that does not exist. after_commit corrects that ordering. If the enqueue happens inside a transaction, use Rails 8.1's documented enqueue_after_transaction_commit behavior explicitly when that is the intended policy, or enqueue from an after_commit callback. Verify the configured Active Job adapter and version rather than assuming all queue implementations have identical persistence behavior.
There is still a crash window when enqueueing is deferred until after commit or the queue uses a separate database: the order can commit, then the web process can stop before the adapter accepts the job. Rails documents that Solid Queue can participate in the same transaction when it shares the application's database and enqueueing is not deferred; the default Rails configuration uses a separate queue database, and other adapters have their own contracts. This example explicitly defers enqueueing, so it does not claim atomic delivery. If losing an event is unacceptable, write an outbox row in the same database transaction as the order, then have a repeat-safe publisher deliver pending rows and mark them only after acknowledged delivery. The outbox creates durable intent, not exactly-once external effects; consumers still need idempotency.
Ruby on Rails 8.1 · Worked example
class FulfillOrderJob < ApplicationJob
self.enqueue_after_transaction_commit = true
def perform(order_id)
order = Order.find(order_id)
Fulfillment.call(order)
end
end
Order.transaction do
order = Order.create!(account: current_account, status: "paid")
FulfillOrderJob.perform_later(order.id)
end
With the setting enabled, Rails defers enqueueing until the surrounding transaction commits and does not enqueue when it rolls back. That prevents a worker from racing ahead of the uncommitted order. If the process exits after the order commits but before the adapter accepts the job, this sketch has no durable second record from which to recover the missed enqueue; use an outbox when that failure must be repaired.
Executed with Rails 8.1.4 and Ruby 3.4.12 against a disposable synthetic PostgreSQL 16 database; all 12 tests passed.
Follow-up: Does a transactional outbox make the consumer perform the effect exactly once?
No. It ensures durable event intent is committed alongside the domain write. A publisher can retry after an uncertain acknowledgement and deliver the same event again, so consumers or downstream APIs must deduplicate by a stable event or idempotency key.
A job times out after charging a card. How do retries avoid charging twice?
Treat a retry as another attempt to run the same logical operation, not as proof that the previous attempt did nothing. Persist a stable operation identity before dispatch, use the payment provider's documented idempotency mechanism when available, and record or reconcile the outcome before issuing another charge. Active Job retry configuration does not make an arbitrary perform body exactly once.
A timeout can happen after a provider accepted a charge but before Rails received its response. Retrying with a new provider key may create a second charge; skipping a retry may leave a valid order unpaid if the provider never received the first request. Use an idempotency key derived from the durable order/payment attempt, bind that key to the exact amount and currency, and query the provider's operation status when the result is uncertain. The key's retention and conflict semantics belong to the provider contract.
Rails 8.1's Active Job offers retry policies such as retry_on, while the queue adapter determines how jobs are stored, reserved, retried after worker failure, and acknowledged. Solid Queue is the Rails default backend starting with Rails 8.0, but applications can use other adapters and configurations. Do not infer one adapter's delivery or retry behavior from Active Job's common interface. Make local database mutations unique or conditional, and test duplicate execution plus a crash after the external side effect but before the job records completion.
Enqueue the durable payment-attempt ID, not the order ID. An order may later acquire another attempt, so resolving its current association again would change the logical operation on retry. The persisted attempt owns the immutable amount, currency and provider key; pass that same attempt identity on every delivery.
Ruby on Rails 8.1; provider behavior is contractual and not assumed · Worked example
class ChargeOrderJob < ApplicationJob
# The client maps connect and response-read timeouts to these exceptions.
retry_on Net::OpenTimeout, Net::ReadTimeout, wait: 5.seconds, attempts: 4
def perform(payment_attempt_id)
attempt = PaymentAttempt.find(payment_attempt_id)
return if attempt.captured?
PaymentGateway.capture(
attempt.amount_cents,
currency: attempt.currency,
idempotency_key: attempt.idempotency_key
)
attempt.update!(state: "captured")
end
end
The durable payment attempt stores the amount, currency and idempotency key before the job runs; those values are treated as immutable for this logical capture, so a later order edit cannot change a retry's payload. The terminal-state check avoids another provider call after the local attempt is recorded as captured. If the provider completed a capture but the local update failed, a retry sends the same attempt payload and key. This is safe only if that provider contract deduplicates the same key for the relevant merchant/account and operation scope, retains it long enough for the retry window, and rejects or clearly reports reuse with a different payload. The client exception names are also illustrative; configure the retry list to the actual provider library's connect and response-read timeout classes. Rails' retry declaration alone establishes neither delivery semantics nor gateway idempotency.
Executed with Rails 8.1.4 and Ruby 3.4.12 against a disposable synthetic PostgreSQL 16 database; all 12 tests passed.
Follow-up: If the payment succeeded but attempt.update! failed, what should the next run do?
Reuse the immutable amount, currency and provider key for that attempt, then reconcile the provider's result before changing local state. Make the local transition conditional and durable so concurrent duplicate jobs cannot both apply a second business effect. The exact recovery flow must match the provider's key scope, retention, payload-mismatch and lookup contract.
A cached invoice fragment contains account-specific fields. How do you avoid cross-tenant leakage and stale content?
Build the cache key from every dimension that changes the rendered result or its authorization context, such as the authorized account, record version, locale and permission version. Still authorize and scope the request before rendering or reading the fragment. A cache key partitions content; it does not grant access or replace an authorization check.
Rails model cache keys commonly include a record identity and, with cache_key_with_version, a version derived from update time. That helps invalidate fragments when the record changes, but it does not automatically include the viewer, account membership or every associated record used in the template. A fragment that displays account-specific pricing or permissions can be stale or shared across principals if its key omits those values. Include the authorized tenant and a version or key representing policy state when those inputs affect output.
HTTP caches are a separate boundary. A private fragment key does not prevent a browser, proxy or CDN from reusing a response under the wrong cache policy. Decide whether the response is public, private or non-cacheable, and set appropriate HTTP caching behavior. For nested fragments, verify that touching a child updates the parent's cache version when intended. Tests should authenticate two tenants and two principals within one tenant, render the same URL or record selector, change a permission or associated value, and prove neither cross-tenant nor cross-principal reuse nor stale output occurs.
Ruby on Rails 8.1 · Worked example
<% cache [current_account.cache_key_with_version,
current_user.id,
current_user.permission_version,
invoice.cache_key_with_version,
I18n.locale] do %>
<%= render invoice %>
<% end %>
Two accounts produce different fragment keys for the same invoice version, and two users in one account also receive distinct fragments even if their permission-version counters happen to match. A permission change or locale change can produce a separate entry as well. The key still does not authorize invoice; the controller must first load it through an allowed relation. If a value used by the partial changes without updating any included version, the fragment can remain stale and needs an explicit dependency or expiry policy.
Executed with Rails 8.1.4 and Ruby 3.4.12 against a disposable synthetic PostgreSQL 16 database; all 12 tests passed.
Follow-up: Should every private response use no-store?
Choose HTTP cache directives based on the data sensitivity and desired browser behavior. private can allow user-agent caching while preventing shared-cache reuse; no-store forbids storage. Neither directive replaces server-side authorization or correct fragment keys.
A customer asks for invoices from their local calendar day. Which clock and query boundary should you use?
Use the application's intended time zone to calculate the local day boundary, then query a half-open interval from that start up to but not including the next day's start. In Rails, Time.current and Time.zone honor the configured or request-specific zone, while Time.now uses the system clock's zone. Persisted timestamps are commonly normalized to UTC, but the product's display and calendar-day meaning remain zone-dependent.
A local calendar day is not always 24 hours. Daylight-saving transitions can make it shorter or longer, and some local wall times are ambiguous or nonexistent. Calculate the start and next start in the relevant zone rather than adding a fixed 24-hour duration to a timestamp. A half-open range, created_at >= start AND created_at < next_start, avoids precision-dependent end-of-day values and composes cleanly with adjacent dates.
The correct zone is a product decision: account zone, user preference or a specified reporting zone. Set that context deliberately and test around daylight-saving transitions and UTC midnight. Do not silently use the server's local zone or assume a database date column represents the same concept as a timestamp. If a report groups stored instants into calendar days, the zone must be part of its query and any associated cache key.
Ruby on Rails 8.1 with PostgreSQL 16 · Worked example
Time.use_zone(account.time_zone) do
day = Date.iso8601(params[:date])
start_at = day.in_time_zone.beginning_of_day
next_start = (day + 1).in_time_zone.beginning_of_day
@invoices = account.invoices.where(
"created_at >= ? AND created_at < ?", start_at, next_start
)
end
For the requested date, Rails computes both local midnights in the account's zone and queries the inclusive lower, exclusive upper interval. PostgreSQL receives timestamp bounds representing those instants; the range can contain 23, 24 or 25 elapsed hours depending on the zone's calendar transition. Invalid dates should be rejected at the request boundary, and the chosen account time zone should itself be validated against the application's supported zone list.
Executed with Rails 8.1.4 and Ruby 3.4.12 against a disposable synthetic PostgreSQL 16 database; all 12 tests passed.
Follow-up: Can the same UTC instant belong to different local reporting days?
Yes. Convert that instant into each intended zone before assigning its calendar date. A daily report's time zone is part of the report definition, not just a display preference.
A controller returns success, but what should a request test prove about the database and error path?
Test the externally visible response and the persisted state that matters, not only an assigned instance variable or a stubbed model call. For an invalid request, assert the chosen error response and that no forbidden write occurred. For a successful request, reload or query the record and verify the stored values and scope, including important database constraints and side effects.
A controller can render a plausible response while saving nothing, saving to the wrong account, or bypassing an expected state transition. An integration test can exercise routing, authentication, parameter filtering, controller lookup and response rendering together. Use separate account fixtures to test cross-tenant access, and assert both the HTTP status and that the other account's row stayed unchanged. Model tests still have value for local validation rules, but they do not prove the whole request boundary.
Database guarantees need tests that reach the database path. A uniqueness validator test covers user-facing validation; a unique-index test or controlled concurrent test covers the final integrity boundary. When callbacks or jobs are involved, assert the intended enqueue or outbox record separately and do not confuse a test adapter's captured job with durable production delivery. Rails test transaction configuration and queue adapters can differ from production, so include integration-level evidence for the behavior that crosses those boundaries.
Ruby on Rails 8.1 test case · Worked example
test "customer cannot update another account's invoice" do
sign_in users(:north_customer)
invoice = invoices(:south_open)
patch account_invoice_path(accounts(:north), invoice),
params: { invoice: { memo: "changed" } }
assert_response :not_found
assert_equal "original", invoice.reload.memo
end
The request uses the authenticated north-account user with a south-account invoice ID. The expected response is 404 under this application's chosen non-disclosure policy, and reloading confirms the persisted memo remains original. The exact authentication helper, route helper and fixtures depend on the app's test setup; the important assertions cross both the HTTP and persistence boundaries.
Executed with Rails 8.1.4 and Ruby 3.4.12 against a disposable synthetic PostgreSQL 16 database; all 12 tests passed.
Follow-up: How would you test a database uniqueness race without making the suite flaky?
Keep deterministic tests for the index and adapter exception behavior, then use a coordinated concurrency test only where the invariant's race behavior needs proof. Synchronize both transactions at the check/insert boundary, assert exactly one persisted row, and avoid relying on timing sleeps. The test database and isolation settings must match the contract under examination.
These are Hacker News job posts that mention these technologies, not employee earnings or a measure of what a skill adds to pay. The amounts summarize annualized advertised minimums in approximate USD. Groups can overlap and differ in roles, locations and dates.
Approximate USD using ECB daily reference rates as of 2026-10-30. Original currencies and offer ranges remain on the source listings. These figures cover posts tagged Ruby on Rails, rather than every job in the broader technology family.