<!-- app/views/user_sessions/show.html.erb -->
<h2>Your Session</h2>
<p>
<%= flash[:notice] %>
</p>
<p>
You're signed in as: <b><%= @current_user.email %></b><br/>
<%= link_to 'Sign Out', user_session_path, method: 'delete' %>
</p>
Finally, we need to add the controller as a resource in our routes file. In your text editor, modify the routes files to match the example below.
# config/routes.rb
resource :user_session
root to: 'user_session#new'
Let’s test our changes. In your terminal, run the rails server
command. Then, open your browser and navigate to http://localhost:3000
. You should see a login form. If the application is working properly you should be able to sign in with the test user that you created in the previous step.
This final step will demonstrate how to test with Authlogic. We’re going to create a user to test with and a functional test that will verify that users can sign in and out of the application.
First, let’s create the test user. In your text editor, modify the users fixture to match the example below.
# test/fixtures/users.yml
josh:
email: josh@example.com
password_salt: <%= salt = Authlogic::Random.hex_token %>
crypted_password: <%= Authlogic::CryptoProviders::Sha512.encrypt('passw0rd' + salt) %>
persistence_token: <%= Authlogic::Random.hex_token %>
Now, let’s write the tests. In your text editor, modify the UserSessionsControllerTest
to match the example below.
# test/functional/user_sessions_controller_test.rb
require 'test_helper'
require 'authlogic/test_case'
class UserSessionsControllerTest < ActionController::TestCase
setup :activate_authlogic
test 'it should sign a user in on create' do
post :create, user_session: {
email: 'josh@example.com',
password: 'passw0rd',
password_confirmation: 'passw0rd'
}
assert_equal 'Sign in successful!', flash[:notice]
assert_redirected_to home_url
end
test 'it should sign a user out on destroy' do
UserSession.create(users(:josh))
delete :destroy
assert_nil UserSession.find
assert_redirected_to root_url
end
end
Let’s test our changes. In your terminal, run the rake test
command. If the tests are setup properly, both should pass.
Congratulations! You should be up and running with Authlogic. For more information about Authlogic, check out the project on GitHub. For a more in-depth example, check out the example application.