Free sample · Chapter 4

Requests, Authentication, Authorization, and Tenancy

Suppose you own an account at Acme, and you send a request that changes a membership belonging to a different company, Globex. You are signed in and the request is well formed. What should happen?

The Minitest application has a test for exactly this:

test/integration/membership_roles_test.rb
require "test_helper"

class MembershipRolesTest < ActionDispatch::IntegrationTest
  test "tenancy: a foreign account's membership is not found and stays unchanged" do
    log_in users(:owner)
    foreign = memberships(:globex_outsider)

    assert_no_enqueued_jobs do
      patch account_membership_path(accounts(:globex), foreign), params: { membership: { role: "member" } }
    end

    assert_response :not_found
    assert_equal "owner", foreign.reload.role
  end
end

The test asserts three things: the response is a 404, the Globex owner’s role is still owner after reloading the row, and nothing was enqueued, which matters here because a successful role change sends mail to the affected user. Each assertion closes a different gap: without the reload, a request that changed the row but answered 404 would pass, and without the queue check, one that queued the mail would too.

Writing that kind of test is the hard part. Successful requests are easy to test and usually get tested by accident, because the feature doesn’t work otherwise, while denials get skipped because nothing breaks visibly when they’re missing.

Seven questions that look like one

"Is this user allowed to do this?" is usually asked as one question. A request pipeline answers several, and each can fail on its own:

  • Identity: who is acting? In the example apps that’s Current.user, resolved from the session.

  • Authentication: has that identity been proven for this request?

  • Membership: does the identity belong to the account named in the URL?

  • Role: what does that membership carry (owner, admin, or member)?

  • Authorization: does the rule permit this action for that role?

  • Tenancy: when the controller loads the record, is the lookup scoped to the account?

  • Entitlement: does the account’s plan allow this action right now?

The two example apps keep these apart, and it’s worth seeing where. Both apps have identical production code, so it’s shown once. The shared filters live in ApplicationController:

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  include Authentication
  ...
  private
    # Tenancy: only accounts the signed-in user belongs to can be found.
    # Anything else raises RecordNotFound, which Rails renders as 404.
    def set_account
      @membership = Current.user.memberships.find_by!(account_id: params[:account_id] || params[:id])
      @account = @membership.account
    end

    # Authorization: what this member may do inside the account.
    def require_manager
      head :forbidden unless @membership.manager?
    end
end

Authentication comes from the generated Authentication concern, which redirects anyone without a session to the sign-in page. set_account is the membership and tenancy check, and it answers with a 404 so a request for someone else’s account looks the same as a request for an account that doesn’t exist. require_manager is role and authorization together, because this application has no separate policy object. A rule like Membership#manager? is the whole policy, and an app that uses Pundit or CanCanCan would pull those two questions apart. Entitlement sits in the invitations controller:

app/controllers/invitations_controller.rb
class InvitationsController < ApplicationController
  before_action :set_account, only: :create
  before_action :require_manager, only: :create
  before_action :require_free_seat, only: :create
  ...
  private
    # Entitlement: the plan, not the person's role, decides this one.
    def require_free_seat
      head :payment_required unless @account.seat_available?
    end
end

The statuses (404, 403, 402) are this application’s choices. Yours might redirect with a flash message for a role failure, or return 404 for both. What carries over is the habit of choosing the outcome deliberately and asserting that one, so the app’s convention is the contract and the test doesn’t assert a status the app never meant to return.

Signing in is one contract, signed-in is another

Before any of these tests can run, the test has to be someone. How it does that depends on how your application authenticates, and that’s an application difference. The example apps use the authentication Rails generates (bin/rails generate authentication), so signing in means posting to the real session route. The helper in the Minitest app is short:

test/test_helpers/session_test_helper.rb
# APP-SPECIFIC: this application uses Rails' generated authentication
# (`bin/rails generate authentication`), so signing in means posting to the
# real session route. Another app would sign in differently.
module SessionTestHelper
  def log_in(user, password: "password")
    post session_path, params: { email_address: user.email_address, password: password }
    assert_redirected_to root_path
  end
end

ActiveSupport.on_load(:action_dispatch_integration_test) do
  include SessionTestHelper
end

The RSpec app has a log_in helper with the same body, written as expect(response).to redirect_to(root_path) and included into request specs. That small difference comes from the matcher syntax. The post session_path line comes from the authentication library, and a Devise app would use sign_in from Devise’s test helpers, a token app would set a header, and an app with an SSO layer would stub whatever its middleware reads. Don’t copy this helper into your repository expecting it to fit. Find your own app’s equivalent and label it as app-specific, so the next reader knows which parts of the test are about your login mechanism.

The login workflow itself gets its own tests, and those shouldn’t use the helper:

test/integration/authentication_test.rb
require "test_helper"

class AuthenticationTest < ActionDispatch::IntegrationTest
  test "signed-out visitor is redirected to sign in and nothing changes" do
    membership = memberships(:acme_member)

    assert_no_enqueued_jobs do
      patch account_membership_path(accounts(:acme), membership), params: { membership: { role: "admin" } }
    end

    assert_redirected_to new_session_path
    assert_equal "member", membership.reload.role
  end

  test "wrong password does not start a session" do
    post session_path, params: { email_address: users(:owner).email_address, password: "wrong" }

    assert_redirected_to new_session_path
    get account_path(accounts(:acme))
    assert_redirected_to new_session_path
  end
end

The RSpec app has the same sign-in tests in spec/requests/authentication_spec.rb, and the reasoning below applies to both. The first test sends a mutating request with no session and checks that the member’s role is unchanged and no mail was queued. The second one posts a bad password and then confirms the visitor still can’t reach a protected page. Both prove the application’s own sign-in behavior: that anonymous requests are turned away, and that a failed attempt doesn’t leave a session behind. What they leave open is everything about the mechanism that doesn’t show up in a single-process test, such as cookie flags, session expiry, the rate limit on the session route, and password reset. Those need their own tests if you care about them, and they’re about authentication, not about the feature under test.

Everything else in this chapter signs in through the helper. That’s fine, because the helper is exercised for real by the two tests above, and an unrelated feature test shouldn’t repeat the login form’s validation. If a helper skipped authentication entirely (by setting Current.session directly, say), denial tests for other features would still work, but you’d want to be sure that the sign-in tests exist somewhere and use the real route.

The same denial in RSpec

The foreign-tenant test from the opening, in the RSpec app:

spec/requests/membership_roles_spec.rb
require "rails_helper"

RSpec.describe "Membership roles", type: :request do
  include_context "two tenants"

  def change_role(account, membership, role)
    patch account_membership_path(account, membership), params: { membership: { role: role } }
  end

  context "tenancy" do
    before { log_in owner }

    it "returns 404 for a foreign account's membership and leaves it unchanged" do
      expect { change_role(globex, globex_outsider, "member") }
        .to not_change { globex_outsider.reload.role }
        .and not_have_enqueued_job

      expect(response).to have_http_status(:not_found)
    end
  end
end

The shape differs from the Minitest version in two ways, and neither is about the tenant logic. The "nothing changed and nothing was enqueued" check sits inside one compound expectation, using two negated matchers defined in spec/support/matchers.rb (not_change and not_have_enqueued_job, built with define_negated_matcher). And the data comes from FactoryBot, through a shared context named "two tenants" that creates Acme, Globex, and one user per role with let and let!. The Minitest app gets the same two tenants from fixtures: memberships(:globex_outsider) is a row in test/fixtures/memberships.yml. Fixtures versus factories is a data-strategy choice (Chapter 9 compares them), not a framework one. What matters for the test is that Globex exists as a named, separate tenant with its own member, so "foreign" is a property of the data and nothing is faked in the request.

Both tests prove that an owner of one account, acting on another account’s membership by its identifier, gets a 404, that the row is unchanged, and that nothing entered the Active Job test queue. They don’t separately prove that a plain member of Acme is turned away from Globex. set_account is the same lookup for every role, so the example apps don’t repeat the case, and the grid later in the chapter records that choice.

There’s a second tenancy test worth having in this controller, and both apps have it: the owner targets a Globex membership id under their own account’s URL. That one doesn’t touch set_account at all. It goes through @account.memberships.find(params[:id]) in the action, which is a different line that can regress separately.

Why the filter order matters

MembershipsController runs set_account before require_manager. That order is part of the contract. If the role were checked first, an outsider could tell which accounts exist from the difference between a 403 and a 404. The acting user in the foreign tests is the owner of Acme, who would pass a role check anywhere they belong, so in this controller a 404 comes from the membership lookup.

Role and entitlement fail differently

Inviting someone to an account is a mutation that can fail for a reason that has nothing to do with who is asking. An account on the free plan has three seats, and Acme has three people, so even an admin is refused. Both applications have a test for it:

test/integration/invitations_test.rb
require "test_helper"

class InvitationsTest < ActionDispatch::IntegrationTest
  test "entitlement: an admin at the seat limit cannot invite, which is not a role problem" do
    log_in users(:admin)
    assert_not accounts(:acme).seat_available?

    assert_no_difference "Invitation.count" do
      assert_no_enqueued_jobs do
        post account_invitations_path(accounts(:acme)), params: { invitation: { email: "new@example.com", role: "member" } }
      end
    end

    assert_response :payment_required
  end
end
spec/requests/invitations_spec.rb
require "rails_helper"

RSpec.describe "Invitations", type: :request do
  include_context "two tenants"

  let(:invite_params) { { invitation: { email: " New@Example.com ", role: "member" } } }

  describe "POST /accounts/:account_id/invitations" do
    it "answers 402 when the plan has no free seat, which is not a role problem" do
      log_in admin
      expect(acme).not_to be_seat_available

      expect { post account_invitations_path(acme), params: invite_params }
        .to not_change(Invitation, :count)
        .and not_have_enqueued_job

      expect(response).to have_http_status(:payment_required)
    end
  end
end

The precondition (assert_not accounts(:acme).seat_available?, expect(acme).not_to be_seat_available) is deliberate. Without it, a change to the fixture or factory that frees a seat would turn this into a test of a successful invite that happens to expect 402, and the failure message would point somewhere unhelpful. The assertions that matter are the unchanged Invitation.count and the empty queue, since an invitation row and an email are exactly what a refused invite must not produce.

The member case is a separate test with a separate status. Minitest shows it as test "authorization: a member is denied with a different status than the seat limit" in the same file, and the RSpec app has the same case. It runs against the same full account, which means it also demonstrates the filter order: a member of a full account gets a 403 and not a 402, because the role check comes first. That’s a decision the application made. If your plan limits should be reported before role denials, you’d write the opposite expectation, and the point of the test is that someone chose.

Together the two tests give you a role failure (403) and an entitlement failure (402) as distinct outcomes. If role and entitlement shared one test with one status, you couldn’t tell which rule had been enforced.

The tenancy rule has to hold on this action too, not only on role changes, because create takes an account id from the URL. Both apps have a short test for it (answers 404 for a foreign account and creates no invitation in the RSpec file, with a matching Minitest test). Every mutating action that loads by identifier needs its own foreign-tenant case, because the filter is attached per action and a new controller can forget it.

Choose the side effect from the threat

A denial test proves three things together: the response, unchanged protected state, and the absence of side effects that the threat could cause. The third is chosen per action, and it isn’t a checklist. Like any test, these are judged by whether they would go red for a realistic defect and stay quiet for a harmless refactor, the lens from Chapter 3.

Changing a role sends mail, so those tests assert an empty queue. Creating an invitation writes a row and sends mail, so the invitation tests check both. Creating a billing customer calls an outside provider. Here the Minitest app asserts that no request left the process:

test/integration/billing_customers_test.rb
require "test_helper"

class BillingCustomersTest < ActionDispatch::IntegrationTest
  test "a denied member makes no provider request and stores no customer" do
    log_in users(:member)

    post account_billing_customer_path(accounts(:acme))

    assert_response :forbidden
    assert_not_requested :any, /api\.payments\.example/
    assert_nil accounts(:acme).reload.provider_customer_id
  end
end

A member isn’t allowed to create the customer (require_owner in that controller), and the threat is that the denial happens after the provider call, which would create a customer at the vendor for an account whose owner never asked. assert_not_requested is a WebMock assertion about Ruby HTTP clients in this test process. It tells you the application’s own code made no request through those clients. It doesn’t cover a request made by another process, and it says nothing about what the provider would have done. The RSpec app has the same case in spec/requests/billing_customers_spec.rb, and WebMock’s assertion is the same in both, so there’s no reason to print it twice.

Mail has its own limit. assert_no_enqueued_jobs and not_have_enqueued_job watch the Active Job test adapter. They show that nothing was queued in this process. If a controller called deliver_now, no job would exist to find and a queue assertion would stay silent, even though an email would be sent. When the threat is "an email goes out", also check what the application actually does to send it, or assert on delivered mail in the same test.

Don’t assert everything. A denied role change doesn’t need a "no provider request" check, because that action never calls a provider, and an assertion for something the code can’t do only adds noise when the code changes.

When the status is the only assertion

A test that checks only the status is easy to write and reads like a denial test:

test "member cannot change roles" do
  log_in users(:member)
  patch account_membership_path(accounts(:acme), memberships(:acme_admin)), params: { membership: { role: "member" } }
  assert_response :forbidden
end

It passes. It also keeps passing if the role check moves from a before_action to a line after membership.update and the mail call in the action, because the controller still answers 403 while the admin has already been demoted and the email has already been queued. Make that change and the status-only test stays green. The member-denial test in membership_roles_test.rb, which also asserts that nothing is enqueued and reloads the target, goes red, and it fails on the enqueue assertion first:

0 jobs expected, but 1 were enqueued.
Expected: 0
  Actual: 1

That the side-effect check fires first says something about the defect. By the time the status could have been wrong, the mail had already gone out. The reload assertion is the one that would report the demotion itself, and it only gets a turn if you take the enqueue check out.

Hidden buttons and policy tests

None of the denial tests here click a button. An application might hide the role form from members, which is reasonable interface design, but a member can still send the PATCH themselves with curl or a stale browser tab. A test that checks the button is gone proves the page is tidy. The denial lives in the request, so that’s where it’s tested.

The other direction has the same gap. Suppose Membership#manager? had its own unit test with every role combination. That would be a good place to keep the permutations, and it would cost almost nothing to run. It wouldn’t tell you the controller calls require_manager, because the filter could be deleted from MembershipsController without that unit test noticing. So the permutations can live in a model or policy test, and each controller action needs at least one request-level denial to prove the rule is wired in.

Deciding which cases deserve a request test

Role, tenant, and entitlement multiply. Take the invitation create action, with five kinds of actor, own or foreign account, and a free or full seat. That’s twenty combinations, and most of them add nothing a neighboring combination doesn’t already show. I find it useful to write the grid down and mark which cases need a request test. The seven rows below group some combinations and leave others unlisted, and the table doesn’t enumerate all twenty.

Actor Account Seat Expected Request test?

Anonymous

any

any

Redirect to sign in

Once per controller, in the authentication tests

Member

own

full

403

Yes (shows role is checked before seats)

Admin

own

full

402

Yes (entitlement alone)

Admin

own

free

Created, mail enqueued

Yes (the success path)

Owner

foreign

free

404

Yes (tenancy)

Member or admin

foreign

any

404

No, same lookup as the owner case

Owner

own

full

402

No, same filter as the admin case

The table is a way to decide, and the combinations that are left out aren’t claimed to be impossible or covered. If a role were allowed to bypass seat limits, owners would need their own row, and the grid would tell you so. Exhaustive permutations belong lower, in a test of Membership#manager? or Account#seat_available?, where each case costs a few lines instead of a signed-in request. The Minitest suite has test/models/account_test.rb for the seat arithmetic, and the RSpec app has the matching model spec.

Wrong identity is its own denial

One more case belongs in this chapter because it is neither tenancy nor role. An invitation is addressed to a specific email address, and the person accepting it must be that identity. A signed-in user with a different email address, who somehow has the link, shouldn’t be able to accept it:

test/integration/invitations_test.rb
require "test_helper"

class InvitationsTest < ActionDispatch::IntegrationTest
  test "someone else's signed-in identity cannot accept: nothing is created" do
    log_in users(:member)
    invitation = invitations(:for_invitee)

    assert_no_difference "Membership.count" do
      post accept_invitation_path(token: invitation.token)
    end

    assert_response :forbidden
    assert_not_predicate invitation.reload, :accepted?
  end
end

The link carries a token, and holding a valid token isn’t the same as being the invitee. The test proves the 403, that no membership was created anywhere, and that the invitation is still pending. It uses one non-matching user; other wrong identities aren’t enumerated. The RSpec app has the counterpart ("refuses someone else’s signed-in identity and creates nothing"). Whether the email address match is enough is a model-level question for the next chapter, where Invitation#accept! is tested directly.

Limits of these request tests

Every test in this chapter runs in one process against a test database, with a fresh transaction and the Active Job test adapter. For the cases written, they show that the application’s own filters answer as intended and leave the database alone. Several things they can’t show:

  • A queue assertion proves nothing was enqueued under the test adapter. It says nothing about a production queue backend or about mail sent inline.

  • Cases that aren’t written aren’t covered. The grid above lists the ones the example apps skip on purpose, and your own grid might skip different ones.

  • A request test goes through the real filters and the real database. It doesn’t go through your reverse proxy, your CDN, or a custom domain that resolves tenants, so a tenant resolved from a subdomain needs its own request setup for that host.

  • Two requests made one after the other don’t show how simultaneous requests would behave, for example two admins using the last seat at the same moment. The seat test above is sequential.

  • Background jobs that receive a record id still have to find that record inside the right tenant. A request test that only enqueues the job doesn’t show that the job does that; the chapter on background work picks it up.