AssertInbox

Test Rails Devise confirmable emails with RSpec and Capybara

Devise's confirmable module sends a confirmation email on sign-up and blocks login until the link in it has been used. Rails' default test delivery method collects mail in ActionMailer::Base.deliveries and never sends it. This guide tests the real path: a system spec with Capybara signs up, the app delivers the email through SMTP to an AssertInbox address, and the spec reads the confirmation link through the API with Ruby's Net::HTTP, visits it and asserts that the user is confirmed. No gems are needed beyond RSpec, Capybara and Devise.

What your app needs

A Rails app with Devise and the :confirmable module on the User model, and RSpec with system specs set up. Mail must really be delivered in the test environment, so set config.action_mailer.delivery_method = :smtp with your test SMTP settings in config/environments/test.rb, instead of the default :test. Use a test SMTP account you control, not a production one. Also set config.action_mailer.default_url_options to a host and port; Devise puts them in the confirmation link. The spec below visits only the path of the link, so the host does not need to be reachable from the test, but it should be the real host in production. The email subject and flash messages come from Devise's locale file and may differ in your app.

How it works

Mail sent to <namespace>.<tag>@assertinbox.com is stored for your key. GET /v1/wait long-polls for up to 25 seconds and returns the newest matching message as JSON, including id, subject, links and magic_link. Messages are deleted after 24 hours.

Get an API key

Get one in a click at /start, or with the request below. One request creates a key and your private namespace. No email address or card is needed. The key is shown once, so store it in your CI secrets.

curl -s -X POST https://assertinbox.com/v1/keys
# {"api_key":"ai_...","namespace":"k3x9a1bz","address_template":"k3x9a1bz.<tag>@assertinbox.com"}

Export both values for the tests: ASSERTINBOX_KEY is the api_key and ASSERTINBOX_NAMESPACE is the namespace. If the call returns 403 signups_closed, the beta is not open for new keys. Use inboxes only for services you own or control; see the terms. Limits and error codes are listed in the limits page.

The helper

Save this as spec/support/assert_inbox.rb. It uses only the Ruby standard library. Each Inbox gets a unique tag, so specs that run in parallel never read each other's mail. wait_for_email accepts the subject and after filters and retries on a 408 timeout.

require "json"
require "net/http"
require "securerandom"
require "uri"

module AssertInbox
  API = URI("https://assertinbox.com")

  class Inbox
    attr_reader :tag, :email

    def initialize(prefix = "rails")
      @tag = "#{prefix}-#{Time.now.to_i}-#{SecureRandom.hex(3)}".downcase
      @email = "#{ENV.fetch('ASSERTINBOX_NAMESPACE')}.#{@tag}@assertinbox.com"
    end

    # Newest matching message as a Hash. Retries on 408, the long-poll timeout.
    def wait_for_email(subject: nil, after: nil, attempts: 3)
      params = { tag: @tag, timeout: 25, subject: subject, after: after }.compact
      attempts.times do
        response = request(Net::HTTP::Get, "/v1/wait", params)
        return JSON.parse(response.body) if response.code == "200"
        raise "AssertInbox returned HTTP #{response.code}" unless response.code == "408"
      end
      raise "No email arrived for tag #{@tag}"
    end

    def clear
      request(Net::HTTP::Delete, "/v1/messages", { tag: @tag })
    end

    private

    def request(verb, path, params)
      uri = API.dup
      uri.path = path
      uri.query = URI.encode_www_form(params)
      req = verb.new(uri)
      req["Authorization"] = "Bearer #{ENV.fetch('ASSERTINBOX_KEY')}"
      Net::HTTP.start(uri.host, uri.port, use_ssl: true, read_timeout: 40) { |http| http.request(req) }
    end
  end
end

The spec

Save this as spec/system/email_confirmation_spec.rb. The field labels, button names and messages are Devise's English defaults; change them to match your views and locale. The spec is skipped when the key is not set, so it does not break a machine that has none.

require "rails_helper"
require "support/assert_inbox"

RSpec.describe "Devise email confirmation", type: :system do
  let(:inbox) { AssertInbox::Inbox.new("devise") }

  before do
    driven_by :rack_test
    skip "ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE are not set" unless ENV["ASSERTINBOX_KEY"] && ENV["ASSERTINBOX_NAMESPACE"]
  end

  after { inbox.clear if ENV["ASSERTINBOX_KEY"] }

  def sign_up
    visit new_user_registration_path
    fill_in "Email", with: inbox.email
    fill_in "Password", with: "correct-horse-battery-9"
    fill_in "Password confirmation", with: "correct-horse-battery-9"
    click_button "Sign up"
  end

  it "confirms the account with the emailed link" do
    sign_up
    mail = inbox.wait_for_email(subject: "Confirmation")

    link = mail["magic_link"]
    expect(link).to include("confirmation_token=")
    expect(mail["subject"]).to match(/confirmation/i)

    # The link host is the one in default_url_options. Visit only its path
    # so that the test hits the Capybara server.
    visit URI(link).request_uri
    expect(page).to have_content("successfully confirmed")
    expect(User.find_by(email: inbox.email)).to be_confirmed
  end

  it "does not let an unconfirmed user sign in" do
    sign_up
    inbox.wait_for_email(subject: "Confirmation")

    visit new_user_session_path
    fill_in "Email", with: inbox.email
    fill_in "Password", with: "correct-horse-battery-9"
    click_button "Log in"
    expect(page).to have_content("confirm your email address")
  end
end

The first example signs up, waits for the email whose subject contains Confirmation, checks that the link carries a confirmation_token, visits it and asserts both the flash message and the database state. The second asserts the other half of the contract: before the link is used, the user cannot sign in.

Why rack_test, and real browsers

The example uses Capybara's rack_test driver because the email path does not need JavaScript. If your sign-up form needs it, use driven_by :selenium, using: :headless_chrome instead. Nothing else changes, since the spec talks to the inbox API and not to the browser. The mail is sent by the app process while the example waits, so the spec must read the email after the click, never before.

Parallel runs and cleanup

The tag includes the time and a random suffix, so parallel_tests workers do not collide. The after hook deletes the messages of the example's tag. If a test sends more than one email to the same address, for instance when you ask Devise to resend the instructions, pass the id of the first message as after in the second wait, so that it returns only the newer one.

Troubleshooting

Next steps

Read Reliable email tests for unique tags, retries and cleanup. Related guides: Django allauth tests, password reset tests and Selenium with Python. The wait filters are described in the docs, and the client files cover Node.js and Python.

Free beta, run by AI agents

This service is in free beta and is operated by AI agents under human supervision. Messages are deleted after 24 hours.