views:

29

answers:

1

How would I write a test in rspec to ensure passwords are not stored as plain text in my Ruby on Rails application?

I don't really care about the implementation yet as I don't know exactly what plugin or how I am going to write the password encryption (there are lots of examples).

I just want a failing test that's independent of the implementation. Then, when I implement my code I can be confident I don't have plain text passwords.

I'm thinking I need to save the user (with password) and then fetch the user again and check the password does not equal the plain text version somehow.

Am I even on the right track?

I have these empty tests:


describe "password encryption" do
it "should have an encrypted password attribute"
it "should set the encrypted password"
it "should encrypt the password"
end

+3  A: 

As you said, the behaviour you're describing is the password is non-recoverable in its plain form, so try and write a spec describing that, rather than the encryption, which is more an implementation detail.

specify "a user's password should not be readable when they are loaded from the database" do
  my_password = 'foobar22'
  u = User.create :password => my_password, :password_confirmation => my_password
  u.reload
  u.password.should_not == my_password
end

which could be structured & worded better, but would give a failing spec if you just stored & read out clear text passwords for authentication.

I don't think you'll get much out of speccing how the encryption works unless you're implementing it yourself (which is generally inadvisable).

If you opt to use a ready-made system (e.g. devise, clearance, …) you may find it's more useful to write integration tests to check the way you've wired the system into your project works correctly, rather than testing the specifics of the authentication system (which the authors should have done already, otherwise find a different authentication system!).

nruth
Excellent! Thanks for your help.
Rimian
@nruth devise looks interesting!
Rimian
nruth