⇤ home

Cucumber and basic authentication

Posted 21 Sep 2009 in Ruby on Rails, Behaviour Driven Design, and Testing

Basic authentication in Ruby on Rails

As a step on my way to learn how to use Behaviour Driven Design as a method of producing a Rails app I thought I’d share with you a useful way of testing basic authentication. One simple way of authenticate a user is to use the built in basic authentication in Ruby on Rails. It’s quite handy when it comes to authenticate you as an admin in a small web app. It’s also quite easy to implement.

app/controllers/application_controller.rb:

class ApplicationController < ActionController::Base
  helper_method :superadmin?

protected
  
  def admin_login_required
    login_success = authenticate_or_request_with_http_basic do |username, password|
      username == "myname" && password == "secret"
    end
    session[:admin] = login_success
  end

  def superadmin?
    session[:admin] || false
  end
end

app/controllers/books_controller.rb:

class BooksController < ApplicationController
  before_filter :admin_login_required
  
  ...
end

This will popup the basic authentication login screen and make the user login when viewing a book.

Now, testing this is pretty easy. I want to point out, that the tests for this are written first, then the actual code as above.

features/step_definitions/books_steps.rb

Given /^I am logged in$/ do
  basic_auth('myname', 'secret') 
end

Related Posts