The login! test helper for Restful Authentication and Machinist

by Trevor Turk

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.

Advertisement