27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Confirmation link sign-in<br />

Listing 6.5 db/migrate/[timestamp]_add_confirmable_fields_to_users.rb<br />

class AddConfirmableFieldsToUsers < ActiveRecord::Migration<br />

def change<br />

add_column :users, :confirmation_token, :string<br />

add_column :users, :confirmed_at, :datetime<br />

add_column :users, :confirmation_sent_at, :datetime<br />

end<br />

end<br />

This migration adds the specified columns to the users table when you run rake<br />

db:migrate or removes them when you run rake db:rollback.<br />

When users sign up, a confirmation token is generated for them. An email with a<br />

link containing this token is sent (and the confirmation_sent_at field is set). When<br />

users click the link, their account is confirmed, and the confirmed_at field is set to<br />

the current time in the process.<br />

You now need to run rake db:migrate and rake db:test:prepare to update your<br />

test database with this latest change. With these fields in place, you should be much<br />

closer to having your scenario pass. Let’s see with a quick run of bin/cucumber features/signing_in.feature:<br />

Scenario: Signing in via confirmation<br />

Given there are the following users:<br />

| email | password |<br />

| user@ticketee.com | password |<br />

And "user@ticketee.com" opens the email with subject "Confirmation<br />

➥instructions"<br />

And they click the first link in the email<br />

Then I should see "Your account was successfully confirmed"<br />

Then I should see "Signed in as user@ticketee.com"<br />

expected there to be content "Created by user@ticketee.com" in "[text]"<br />

Everything but the final step is passing. The final step checks for “Signed in as<br />

user@ticketee.com” somewhere on the page, but it can’t find it. You must add it to<br />

your application’s layout, replacing the Sign Up link with “Signed in as [username]”<br />

so users don’t have the option to sign up if they’re already signed in!<br />

Let’s open app/views/layouts/application.html.erb and change this line<br />

<br />

to the following:<br />

<br />

Signed in as <br />

<br />

<br />

<br />

The user_signed_in? and current_user methods are provided by Devise. The<br />

user_signed_in? method returns true if the user is signed in; otherwise it returns<br />

false. The current_user method returns a User object representing the current<br />

user, and from that object you can call the email method to display the user’s email.<br />

125

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!