I am fairly new to Rails, but from what I have learned thus far, its fantastic. I plan on posting more obscure Rails items as I come across them.
I am writing an application that is similar in functionality to Yelp (in some ways). I have had some help along the way from a seasoned Rails vet. One of the things he helped me with was setting up the sessions_controller. He did this in such a way that I wasn’t initially sure how to write the functional tests for it. The sessions_controller contained code like this (it’s a bit more in depth than this, but this will give you the idea):
1 2 3 4 5 6 7 8 | def create @current_user = User.find_by_username( params[:username] ) if @current_user.nil? or Digest::SHA256.hexdigest( params[:password] + @current_user.password ) != @current_user.password_salt redirect_to( login_path ) else redirect_to( user_path ) end end |
So when it came time to write the functional tests for this (using fixtures), I couldn’t get away with just a user.yml like this:
1 2 3 4 5 6 7 8 | test_user: username: test_user password: secretuser firstname: General lastname: User email: test_user@user.com role: normal nickname: Mr. Testy |
The reason for this is because the user table contains an extra column pertaining to the password called password_salt (which you’ll notice referenced above). Therefore my user fixture needed to look something more like this:
1 2 3 4 5 6 7 8 9 | test_user: username: test_user password: A0Mrhnu4 # secretsalt password_salt: 868532ea243f03c2ce5f6f99dcf9e27342c39ce51819fa0605302ab4b5c3841e firstname: Test lastname: User email: test_user@example.com role: normal nickname: Mr. Testy |
The other fixture still has it usefulness in testing (like testing logins that won’t work), so don’t get rid of it so quickly.
How do I generate that salt and the hashed password? I’m glad you asked. I’m sure there is a better way to do it than I did, but I just went into the application, created a user and then went into the console, grabbed the user information and copied it into the fixture. Then I used the following code in my sessions_controller_test.rb for the functional test:
1 2 3 4 5 | def test_should_logout_and_clear_session post :destroy, :username => 'test_salt', :password => 'secretsalt', :return_to => '/' assert_redirected_to '/' end |
