The login! test helper for Restful Authentication and Machinist

Posted by Trevor in Ruby/Rails on February 12, 2009

A recent blog post reminded me that I should share a little test helper we've been using quite happily at the office lately. This trick works great with our extra-restful Restful Authentication and fixture-free Machinist setup.

It creates a new user with Machinst, and then logs the user in. We add a touch of convenience by returning the user object, and finish off by allowing you to pass in extra options if necessary.

 
def login!(options = {})
  user = User.make(options)
  @request.session[:user_id] = user.id
  user
end
 

This allows for many little niceties in your tests:

 
# login as a newly created user
login!
 
# login and keep the user around for assertions and whatnot:
user = login!
 
# login with admin privileges
login!(:admin => true)
 

It's a small thing, but give it a try! I'm sure you'll like it.

6 Comments

 ZDZolton

YTMND!!

 Mischa

Trevor, in this case, I definitely agree that it’s clarifying to have a bang here.

Maybe the rule for idiom should be like this:

Use a bang if:

An activerecord model is changing something in the db.

A activerecord model is saving or failing (e.g. create!, save!)

A method is changing session state in a test.

Hmm, what else?

 zerohalo

I like.

 Keith

Would you mind sharing the code inside your User.make, i’m curious how you deal with Machinist and the password/salt hashes.

thanks

 Trevor

Keith, I’m not doing anything special, I don’t think: http://gist.github.com/137125

 Kiran

This was super helpful thanks for the information. I tried this with machinist and did find a couple things different from the default install of restful_auth

1. The blueprint has username and my user had login instead of username so my blueprint looks like the below

User.blueprint do
login
email
password ‘monkey’
password_confirmation “#{password}”
activation_code nil
end

Also here is the sham definition for people that care:

Sham.define do
email { Faker::Internet.email }
login { Faker::Internet.user_name }
end

The reason for the setting the activation_code to nil is so that my tests dont generate the emails that happen as observers during signup. I had to change the default user observer that restful_auth puts in to be the following

def after_create(user)
UserMailer.deliver_signup_notification(user) if user.active?
end

Hope that helps others get a passing set of tests

Leave a comment

WP_Big_City