← Back to articles

Rails Practices Worth Keeping

November 27, 2026

railsrspectesting

A new Rails action is a few lines. The wrong one is also a few lines.

The action loads an event by id and renders it. The spec signs in as the organizer, builds that organizer's event, and expects success. Another user can pass the first user's event id and get the same response. The suite is green. The framework already had a place for the check. The spec never asked for the denial.

The practices below are how I keep that from turning into a style argument. They are the ones I use on Juntos Family, a Rails 8 app for private events, and on uButeco, a multi-tenant restaurant API. Both are public.

1. The Rails Guide is the default

The standards file on Juntos has one rule I still quote in review: when the choice is between a pattern you are inventing and the Rails Guides, follow the Guide.

The Guides are the framework's own account of routing, Active Record, migrations, security, and testing. The Rails doctrine is why they read the way they do. Convention over configuration means a name and a directory are already a decision. The omakase default means the stack that ships with Rails is the one you diverge from on purpose, with a reason you can point at.

"The Rails way," in a pull request, is that set of conventions applied to the change in front of you:

  • A thing you create, read, update, and delete gets a resources route.
  • Mass assignment goes through strong parameters, with an explicit permit list. The security guide is the reference I send people to, because a missed attribute is how user_id and admin end up writable.
  • Validations live on the model. A custom validator gets its own class once the model method stops being readable.
  • The controller authenticates, authorizes, hands off, and responds. EventsController#create assigns the current user, saves, and redirects.
  • A service exists when the step is a workflow with its own failure cases. Redrawing a Secret Santa is a service. Wrapping every save in an object is a layer the Guide did not ask for.
  • Jobs, mailers, and locale files stay in the directories Rails already created.
  • A listing that touches an association uses includes or preload.

RuboCop on Juntos inherits rubocop-rails-omakase. A style point the cop already enforces does not need a paragraph in the review.

2. RSpec is where the behavior is specified

On these apps the test framework is RSpec. The Juntos Gemfile group is rspec-rails, factory_bot_rails, shoulda-matchers, simplecov, and fuubar. The coverage floor I set is 80% of lines. A covered line that never asserts the other user's denial has not specified the behavior I care about.

I split specs by the object they exercise:

  • Model specs for validations, scopes, and callbacks.
  • Service specs for a workflow.
  • Request specs for the status, the redirect, and the body or the flash.
  • An ability spec for who may do what.

Controller specs are the copy I skip. A request spec drives the router, the callbacks, and the response. A system spec is for a path the browser has to prove. The Rails testing guide already pushes you toward the level where the behavior is visible. A third suite under spec/controllers restates the request spec more slowly and with less of the stack.

New specs use expect(...).to. I lock a new project to that syntax so should cannot creep back in:

RSpec.configure do |config|
  config.expect_with :rspec do |c|
    c.syntax = :expect
  end
end

The example name is present tense. "does not manage other users events" is something a failure can quote. "should not manage other users events" reads like a wish.

3. Better Specs, and the half that aged

Better Specs is a community checklist for readable RSpec. It started at Lelylan. The page says so, and it also says some of its advice needs updating. I use it as a review list. I do not treat every section as current.

These parts still earn their place.

Name the method. Class methods get . and instance methods get #, the same convention as Ruby's own documentation. describe ".authenticate" and describe "#admin?" tell you which method failed. "the authenticate method for User" makes you parse a sentence first.

A context starts with when, with, or without. The condition is the context. The example is the outcome. Two it blocks that each bury "if logged in" in the name are one context that was never written.

One behavior in a unit example. Better Specs is specific here, and the specificity matters. In an isolated example, two expectations usually mean two behaviors, and the failure points at the first one only. In a slower example that already paid for a database round trip, checking the status and the body of the same response is one behavior with two observations. The page says that outright. A request spec that also creates a second record "while we are here" has left that exception.

Specify the case that must fail. Their destroy sketch is the shape I want on an authorization change: the resource is found, the resource is missing, the resource is not owned. The happy path will get written. The unowned id will not, unless it is an example of its own.

Prefer let to an instance variable set in before. let is lazy and memoized for that example. let! runs before the example, which is what a scope spec needs when the row has to exist before the query. A named subject is worth it when several examples share one object. The ability spec does this: subject(:ability) { described_class.new(user, participant: guest) }.

Create only the rows the example reads. A scope called .top(2) needs three users, not thirty. If the example seems to need a crowd, the assertion is probably about the wrong thing.

Exercise the real object. Stubbing the method under test turns the spec into a check that the stub was called. Stub the network boundary, with WebMock or the equivalent, when the example is about how your code reacts to another service.

The rest of the page I treat as history.

The 40-character cap on descriptions is a formatting preference. I split an example when the name contains a condition that belongs in a context. I do not count characters. "cannot create events when at the active event limit" is a long name, and it is the right name, because the condition is the whole point of that example.

"Use factories and not fixtures" is too broad for the suite I actually run. Juntos loads every fixture for every example, through spec/support/fixtures.rb, and uses Factory Bot where the example needs a variation. users(:ana) and events(:natal) are a stable cast. The limit example calls create(:event, user: user) twice so Ana is already at the cap. A fixture file is a bad place for that graph, because every example in the suite would build it. A factory is a bad place for Ana, because every ability example would rebuild a person the fixture already named.

"Test what you see" was an argument against controller specs, aimed at Capybara for the whole suite. I still skip controller specs. I do not skip request specs. A system spec is the wrong tool for "another user receives a denial," because it is slower and farther from the status code.

Shared examples pay off when the contract really is shared: a tenant-scoped index returns 404 for another organization, on every product controller. They hide the example when they are only there to DRY up two model specs that look alike.

Spork, Zeus, and a Guardfile as the way to make the suite fast belong to an older Rails. The speed advice that still holds is the one in the "create only the data you need" section, plus a command that runs the file you are editing. bundle exec rspec spec/models/ability_spec.rb is that command. Fuubar, as the formatter, is the part of the tooling section I kept.

4. Factory Bot names a state

The event factory on Juntos stays small. The base factory is a future event with an owner. The expensive graph is a trait. This is the :drawn trait, with the description line of the base factory left out:

factory :event do
  association :user
  title { "Amigo Secreto" }
  event_on { 1.month.from_now.to_date }

  trait :drawn do
    after(:create) do |event|
      giver = create(:participant, :confirmed, event: event, name: "Alice", email: "alice@example.com")
      receiver = create(:participant, :confirmed, event: event, name: "Bob", email: "bob@example.com")
      draw = create(:draw, :completed, event: event)
      create(:draw_assignment, draw: draw, giver: giver, receiver: receiver)
    end
  end
end

An example that says create(:event, :drawn) is asking for a completed draw. An example that says create(:event) is not, and it does not pay for Alice, Bob, and an assignment. That split is the whole point of the trait. Factory Bot's getting-started guide is the reference for the mechanism: traits, associations, callbacks, and sequences.

The review checks I use on a factory change:

  • The attribute the example cares about is set at the call site. create(:event, user: user) says the owner matters. A factory that quietly picks an owner hides the arrangement the assertion depends on.
  • create inserts a row. build does not. The example that needs an id, a query, or an after_create callback uses create. The example that only needs a valid object in memory uses build.
  • A callback that creates more records sits on the trait that needs those records. The base factory does not draw a Secret Santa as a side effect of existing.
  • The factory does not assert. An expectation inside after(:create) has left the spec.
  • A unique column uses a sequence. Two create(:user) calls cannot both land on the same email.
  • The trait name is a state you can say out loud: :confirmed, :ready_to_draw, :drawn.

FactoryBot.lint is worth a run once factories fail for reasons the example never set. A trait with no caller is a second way to build the same event. I would rather delete it.

5. CanCanCan keeps the denial next to the grant

Authentication on Juntos is Devise. Authorization is one Ability. The class takes the signed-in user and, for an invite link, the participant that token resolved. ADR 0010 records why: organizer, guest, and invitee were scattered across controllers, and a new action could forget a check. Pundit was considered and left aside because the team had already chosen CanCanCan. Rolify was more roles than the app has.

The rules that can become a query are hashes. This is the organizer slice:

def organizer_abilities(user)
  can :create, Event if Users::EventEntitlement.new(user).can_create_event?
  can :manage, Event, user_id: user.id
  can :manage, Participant, event: { user_id: user.id }
  can :manage, Draw, event: { user_id: user.id }
  can :manage, DrawExclusion, event: { user_id: user.id }
end

A block looks like the same rule and behaves differently. Defining Abilities is explicit: a block passed to can is used when you already have an instance. It is not used to scope a class, so load_and_authorize_resource and accessible_by cannot turn it into SQL. An index that loads every event and trusts the block to filter will leak rows. can :manage, Event, user_id: user.id is the form the index can enforce.

uButeco applies the same constraint per role. AdminAbility manages a Beer only with organization_id: user.organization_id. A product rule without that condition is a cross-tenant read. Separate ability classes keep a cash-register role from inheriting an admin's grants. They do not replace the organization condition. Every tenant-owned rule still names the tenant.

check_authorization on ApplicationController fails the request when an action never called authorize!. The exempt list is short: Devise, the OAuth callbacks, Google account linking, the PWA controller, and the public pages (landing, errors, legal, seo). A new controller is checked because it is absent from that list.

load_and_authorize_resource fits a REST action whose instance is the record being authorized. The events index is the case I carved out. It calls authorize! :read, Event, then loads current_user.events. The collection is the owner's association. An ability spec does not run that query. A request spec signed in as two different organizers does. Authorizing controller actions covers both styles. The choice is to use the loader when the resource is the authorized object, and to authorize the action yourself when the collection is a scoped association you are about to write by hand.

can? in a template hides a button. The action still needs the load callback or an authorize!. Guests are never granted :manage on Event. Hiding the edit link is a courtesy. It is not the check.

The ability spec uses the matchers from cancancan. Each context is a kind of actor. Each example is one grant or one denial. This is the organizer pair, unchanged:

describe "organizer" do
  let(:user) { users(:ana) }
  let(:own_event) { events(:natal) }
  let(:other_event) { events(:bruno_bbq) }

  it "manages own events" do
    expect(ability).to be_able_to(:manage, own_event)
  end

  it "does not manage other users events" do
    expect(ability).not_to be_able_to(:manage, other_event)
  end
end

The second example is the one that would have caught the action in the opening. be_able_to(:manage, own_event) passes for an ability that says can :manage, Event with no owner. The denial is the assertion that makes the owner condition real.

rescue_from CanCan::AccessDenied redirects with an alert. ActiveRecord::RecordNotFound renders a 404. A spec that accepts either outcome will stay green when a missing id and a forbidden id collapse into one response. On a server-rendered app I redirect the denial. On an API I prefer 404 for another tenant's id, so the body does not confirm that the row exists. Pick the one the app already uses, and assert that one.

6. One change, in that order

A new nested resource, reviewed as a single diff, goes in this order.

  1. The route is a resources line. Strong parameters list the attributes a person may send. The owner is assigned from the session, and it is absent from the permit list.
  2. The ability gains a hash condition for the owner. It does not gain a rule that grants the same action to every signed-in user.
  3. The ability spec has the grant and the denial before the controller grows around them.
  4. A factory trait shows up only when the example needs a state the base record does not have. The call site sets the attribute the example is about.
  5. A request spec signs in as the owner and as someone else. The someone else is the example that has to fail. A missing id is a separate example, with the status the app already uses for not-found.
  6. The template calls can? after the controller check is in place.

On Juntos, bin/ci runs RuboCop, bundler-audit, Brakeman, and the suite before a pull request. I read the denial example and the permit list before I read the markup.

Closing

The Guide decides where the code goes. RSpec, read with the half of Better Specs that still matches how a suite fails, decides the shape of an example. Factory Bot builds the state that example named, and leaves the stable cast to fixtures when you already have one. CanCanCan keeps the grant and the denial in one class, in conditions a query can enforce, and the spec that matters is the denial.

The next time a review starts inventing a layer, I will send it to the Guide. The next time a spec is only the happy path, I will ask for the example where the other user is rejected.

References

An assistant helped draft this page. I am responsible for what it claims.

Lucas Sartori

Lucas Antonio Ramos Sartori

Senior Ruby on Rails Engineer | Backend Architecture | PostgreSQL | Performance & Reliability

Senior Rails/backend engineer with 9+ years stabilizing and scaling mature SaaS systems — reliability, performance, test coverage, architecture, and production safety. I work with U.S.-based companies remotely from Brazil. Recent work includes event-driven search/indexing, legacy modernization, and AI workflows where they cut cost and latency.