Friday, February 4, 2011

Rails 3.0: Devise + Mongoid + RSpec

Devise removes the mundane job of writing all the code required to handle a user account. Plus, it supports Mongoid.

The following is a non-exhaustive list of tasks Devise takes care of for you:
  • signup
  • forgot/reset password (including emails)
  • confirmation emails
  • password encryption
  • login
  • logout
  • editing account info
  • locking accounts
  • session expiration

All this is available out of the box. Along with the goodies that are pre-packaged, Devise is fully customizable.

Installation

Open Gemfile
gem 'devise'

Install
bundle install
rails generate devise:install

You will need to setup your mailer if it isn't already setup. Devise depends on the default host being set, so ensure the following is set
# ... other mailer settings
config.action_mailer.default_url_options = { :host => 'localhost:3000' }

Don't worry! Devise is smart and has already detected that you are using Mongoid at this point and not ActiveRecord. It has also created config/initializers/devise.rb. This is where you can configure Devise. Take some time to familiarize yourself with all the options and uncomment any that you would like to use. I'll wait.

Test Helpers

If you are using RSpec, create spec/support/devise.rb with
RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end

Now you have access to things like
sign_in @user
sign_out @user

Create a User model

It is time to create a User!
rails generate devise user

This generates a user model at app/models/user.rb with some Devise specific lines of code. Include the modules that you want and remove the ones you don't.

Believe it or not, Devise is now properly hooked up and ready!

Routes

Devise automagically generates all the user routes required for handling the user account. If you look in config/routes.rb, you'll notice
devise_for :users

To see all the routes
rake routes

You will notice a bunch of user routes. Fire up your server and navigate to localhost:3000/users/sign_up. Voila!

As a quick reference, here are some useful routes:
  • signup: new_user_registration_url
  • edit account: edit_user_registration_url
  • login: new_user_session_url
  • logout: destroy_new_user_session_url

References

I encourage you to take a look at the Devise home page as there is a wealth of information there.

https://github.com/plataformatec/devise

1 comment:

  1. I've got a useful
    rails3-mongoid-devise example app with a detailed tutorial on GitHub that shows how to solve a few of issues that can come up with Devise + Mongoid + RSpec. Plus it has some ready-to-run RSpec specs and Cucumber features.

    ReplyDelete