guest@websec: ~/websec/r10-testing — zsh — 100×40 by SaKKo YouTube ENTH

guest@websec ~ % man r10-testing

Testing the API

We test with Minitest, the Rails default. Model tests check rules; integration tests call real endpoints through named route helpers and check status and JSON.

Test data rules and edge cases in model tests, and test every API endpoint end-to-end in integration tests using named route helpers — covering happy path, 401 unauthenticated, 403 forbidden, 404 cross-tenant scoping, and 400 invalid input.

Layout

test/
├── test_helper.rb                     # loads Rails, fixtures :all, parallel workers
├── support/admin_integration_test.rb  # base class for admin endpoint tests
├── fixtures/*.yml                     # sample rows, one file per table
├── models/role_test.rb                # ActiveSupport::TestCase
├── services/token_service_test.rb
└── controllers/api/v1/admin/roles_controller_test.rb   # ActionDispatch::IntegrationTest
ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"
require_relative "support/admin_integration_test"

module ActiveSupport
  class TestCase
    parallelize(workers: :number_of_processors)
    fixtures :all
  end
end

Fixtures

# test/fixtures/client_applications.yml
one:
  name: HR Portal
  app_key: key_one
  api_secret: secret_one

# test/fixtures/roles.yml
one:
  client_application: one          # refer to another fixture by label; Rails fills the uuid
  name: MyString1
  status: active

Every test starts with these rows loaded, inside a transaction that is rolled back afterwards. Read them with roles(:one), client_applications(:one).

A model test

require "test_helper"

class RoleTest < ActiveSupport::TestCase
  def setup
    @client_app = client_applications(:one)
    @client_app.permissions.create!(name: "reports:view")
  end

  test "is invalid when permissions contain strings not in client_application.permissions" do
    role = @client_app.roles.new(name: "intruder", permissions: ["reports:view", "admin:destroy"])

    assert_not role.valid?
    assert_includes role.errors[:permissions], "contains invalid permissions: admin:destroy"
  end
end

An integration test

require "test_helper"

class Api::V1::Admin::RolesControllerTest < AdminIntegrationTest
  setup do
    @admin_user = users(:one)
    @client_application = client_applications(:one)
    @role_one = roles(:one)
  end

  # ============================================================================
  # POST #create
  # ============================================================================

  test "POST #create creates a role and sets client_application_id from the URL" do
    sign_in_as_admin(@admin_user) do
      assert_difference -> { @client_application.roles.count }, 1 do
        post api_v1_admin_client_application_roles_url(client_application_id: @client_application.id),
             params: { role: { name: "Content Manager", permissions: [] } }
      end

      assert_response :created
      json_response = JSON.parse(response.body)
      created_role = Role.find(json_response["role"]["id"])
      assert_equal @client_application.id, created_role.client_application_id
      assert_equal created_role.as_admin_json.as_json, json_response["role"]
    end
  end

  test "POST #create returns 400 when the role key is missing" do
    sign_in_as_admin(@admin_user) do
      post api_v1_admin_client_application_roles_url(client_application_id: @client_application.id),
           params: { name: "Direct Param" }

      assert_response :bad_request
      assert_equal "ActionController::ParameterMissing", response.parsed_body["type"]
    end
  end
end
piecewhat it does
post …_url(…), params:, headers:sends a real request through routing, middleware, filters and the action
assert_response :createdchecks the status (:ok, :not_found, :bad_request…)
JSON.parse(response.body) / response.parsed_bodythe JSON as a Hash with string keys
assert_difference -> { … }, 1 doproves a row was (or wasn't, with assert_no_difference) created
record.reloadre-read after an update to check what was saved
x.as_admin_json.as_jsoncompare with the model's own serializer, so tests don't hard-code every field

Named paths inside tests

Integration tests include the route helpers, so use them instead of typing URL strings. Pick any route below to get the helper call and a test line, with required ids filled from the path:

route → helper → testclick a row
  • Rename-safe: change a path in routes.rb and every test follows. Remove a route and tests fail loudly with NoMethodError instead of quietly hitting 404.
  • Self-documenting: required segments are keyword arguments, so client_application_id: in the call shows the nesting.
  • Use _url in tests (our convention); _path works too. Query params go in the helper (api_v1_admin_users_url(page: 2)) or in params: for GET.

Our test helpers

AdminIntegrationTest

class AdminIntegrationTest < ActionDispatch::IntegrationTest
  DEFAULT_CUSTOM_HEADER = "XMLHttpRequest"

  # every write request gets X-Requested-With automatically...
  [:post, :put, :patch, :delete].each do |method_name|
    define_method(method_name) do |url, **args|
      args[:headers] ||= {}
      unless args.delete(:skip_custom_header)          # ...unless a test opts out
        args[:headers]["X-Requested-With"] ||= DEFAULT_CUSTOM_HEADER
      end
      super(url, **args)
    end
  end
end

# negative test:
post api_v1_admin_client_applications_url, params: {...}, skip_custom_header: true
assert_response :forbidden

Signing in without the real login backend

def sign_in_as_admin(user)
  Api::AppController.define_method(:fetch_cookies) { |_type| "mock_jwt_token" }   # any cookie
  User.stub :find_by_jwt, user do                                                 # resolves to this user
    user.stub :is_admin?, true do
      user.stub :jwt, "refreshed_mock_jwt_token" do
        yield
      end
    end
  end
ensure
  Api::AppController.remove_method(:fetch_cookies) if Api::AppController.instance_methods(false).include?(:fetch_cookies)
end

Minitest’s stub replaces a method only inside the block. The real set_current_user and check_permissions still run, so permission logic is tested for real.

Client API tests

setup do
  @client_application = client_applications(:one)
  @headers = {
    "X-App-Key" => @client_application.app_key,
    "X-App-Secret" => JWT.encode({ sub: @client_application.app_key }, @client_application.api_secret, "HS256"),
  }
end

test "GET #index returns unauthorized when authentication headers are missing" do
  get api_v1_client_roles_url
  assert_response :unauthorized
end

Running tests

What to test for every endpoint

  • happy path: status, JSON equals as_*_json, database changed
  • validation failure → 400 with details, assert_no_difference
  • missing wrapper key → 400 ParameterMissing
  • unknown id → 404; id from another parent → 404 (IDOR)
  • not signed in → 401; signed in without the permission → 403
  • invalid state transition → 400 AASM::InvalidTransition

Check yourself

Why do our controller tests call api_v1_admin_client_application_roles_url(client_application_id: id) rather than "/api/v1/admin/client_applications/#{id}/roles"?

A typo in a string is a silent 404; a helper raises NoMethodError or UrlGenerationError.

How do you test that a POST without X-Requested-With is rejected, using AdminIntegrationTest?

The overridden post adds the header unless you opt out with skip_custom_header: true.