Logging in
Now that we have signed up to the application, we want to be able to actually log in.
The log in process is about:
Accessing an interface that allows the user to provide his credentials (the log in page)
Checking and validating the credentials (in our case querying the database and comparing the provided email and password to whatever we have stored)
If successful, telling the application that a user is logged in
Making the user data available to the application (in our case storing the user id in the
sessionand/or in a global variable)
We start with high level acceptance tests simulating the actions of a user that wants to log in. Add the following scenario to the user_maintenance.feature:
# features/user_maintenance.feature
Scenario: Log in to the application
Given I am a registered user
Given I am on the home page
And I click "Log in" link
Then I should be on Log in page
And I fill in "Email" with "thomas@random.com"
And I fill in "Password" with "my_password"
And I click "Submit" link
Then I should be on the home page
And I should see "Successfully logged in Thomas"
And I should not see "Register"Add the following step definition, reusing some previous steps:
Run cucumber (cucumber features/user_maintenance.feature)
Update your application.erb by adding the Log in link:
And add that path to paths.rb so Cucumber knows where to go:
Add the following routes to application.rb
Create a login.erb file in the views/users folder:
Shifting our attention to the User model. We need to add a authenticate method to User.
Let's start by writing some specs.
Again, run rspec and see the tests fail.
Add the authenticate method to the User class:
These test will still fail...
We need to add DatabaseCleaner to the spec_helper.rb
And now all the tests go green.
Back to the main controller. Change the post route to:
Also, in the same file, we need to add some methods to be able to access the currently logged in user:
We only want to show the Log in link if there is no user logged in, right? Update your application.erb by adding a condition for the display of the Log in link:
If you run cucumber now, all your steps should go green. Time to set up the log out feature.
Last updated