In my last post I went through how to set up Warden with a Sinatra app for authentication. However, once you’ve done that any tests you’ve written for those now authenticated routes and controllers in Sinatra will break because of course the authentication will prevent the controller actions from executing. Fortunately Warden’s Spec helpers make this a pretty easy update.

First, let’s take a look at one of the routes we previously set up before authentication.

class YourApp
  get "/protected_pages" do
    erb 'admin_only_page'.to_sym
  end
end

A test to make sure this page loaded correctly would look like this:

describe "YourApp Pages" do
  it "should load the admin_only_page" do
    get "/protected_pages"
    last_response.should be_ok
  end
end

But once we added in Warden our route would look like this:

  get "/protected_pages" do
    check_authentication
    erb 'admin_only_page'.to_sym
  end

and the test would fail.

In order to log in users for any of your specs you just need to tell the RSpec config to include the Warden Test Helpers. For a Sinatra app you already need to set up the Rspec config to use use the Rack::Test::Methods so you can add the Warden line right after that. (This whole block goes inside the spec_helper.rb file inside of your spec folder.)

RSpec.configure do |config|
  config.include Rack::Test::Methods
  config.include Warden::Test::Helpers
end

Once you’ve added this to the spec_helper you can use the login_as command anywhere in your tests that you’ve set up a user that needs to login. So, this is how we might configure our new test (using a MockUser):

describe "YourApp Pages" do
  it "should load the admin_only_page" do
    @user = MockUser.new(:email => "test@test.com", :password => "password", :admin => true)
    login_as @user
    get "/protected_pages"
    last_response.should be_ok
  end
end

If the check_authentication method that we set up checks that it’s a legitimate user and that they are an admin, this test should pass since the Warden helper logs in our @user and grants them access.

Warden helpers are built to automatically include login and logout but also allow you to build custom helpers. For a quick rundown head over to the Warden wiki.