Mihai Anca
Clearance - login with username

For my Rails projects currently I’m using Thoughtbot’s stack (Shoulda, factory_girl) and now I switched to Clearance. I love it because it’s tested and it’s easy to extend. One such modification that I need is to allow users to login with username. I wrote a demo app and here’s a tutorial on how to do it yourself:

1. Install clearance and run the generator

2. Test UsersController#new includes a username (or “handle” or whatever) text field

test/functional/users_controller_test.rb

And watch it fail:

test: The public When getting new User view should display username field. 
(UsersControllerTest) [/test/functional/users_controller_test.rb:11]:
There must be a username field.
<false> is not true.

Add the field to app/views/users/_form.html.erb to fix it (it still won’t pass because the model does not have the username field yet):

  <%= form.label :username %>

<%= form.text_field :username %>

3. Create migration to add username:

$ script/generate migration AddUsernameToUsers username:string

$ rake db:migrate

And update the factory test/factories/clearance.rb:

4. Test the User model to validate presence of username and to allow mass assignment

test/unit/user_test.rb should be:

Now the unit tests are failing, to fix them we need to add validations to the User model and make the username field accessible:

5. Test SessionsController#create that given a User’s username for the :email value, the User should be signed in

Which fails because we only check email. Add a test for the User#authenticate method so it checks email too:

Add the implementation to the User model and all tests pass:

Please post your suggestions/comments, this post was written at 2am and it may have inacurracies.

  1. basti reblogged this from ropiku
  2. ropiku posted this
Blog comments powered by Disqus