sajad torkamani

Suppose you’re using Devise to implement authentication. You have the usual before action hooks to authentication controller actions. But, how do you test that a given route has the authentication check in place. Here’s an approach:

Write custom require_authentication matcher

RSpec::Matchers.define :require_authentication do
  match do |given_proc|
    given_proc.call

    page.has_current_path?(new_user_session_path) &&
      page.has_text?(unauthenticated_message)
  end

  supports_block_expectations

  failure_message do
    <<~MSG
      expected a redirect to #{new_user_session_path} and for the message#{' '}
      \"#{unauthenticated_message}\" to be shown.
    MSG
  end
end

Use custom matcher

# frozen_string_literal: true

require 'rails_helper'

RSpec.describe 'Create note', type: :feature do
  it 'requires user to be authenticated' do
    expect { visit new_note_path }.to require_authentication
  end
end