2012-04-29 14 views
6

Questo capitolo aggiunge i token di memoria per garantire che lo stato di accesso dell'utente venga memorizzato e che la sessione venga cancellata solo quando l'utente si disconnette esplicitamente. Capisco l'importanza di avere questa funzionalità nella mia app, quindi voglio assicurarmi che funzioni correttamente. Sto ricevendo un sacco di errori, però, quando corroCapitolo 8 Esercitazioni sulle rotaie Memorizza gli errori dei token

$ bundle exec rspec spec/ 

e ho il sospetto che hanno a che fare con il mio modello di utente, in quanto contengono tutti tranne uno:

NoMethodError: 
     undefined method `remember_token=' for #<User:...> 

e l'ultimo contiene

Failure/Error: it { should respond_to(:remember_token) } 

e poi puntare ai miei user_spec.rb, user.rb, e file e authentication_pages_spec.rb, che ho incluso la maggior parte dei (le parti pertinenti) qui.

user.rb:

# == Schema Information 
# 
# Table name: users 
# 
# id   :integer   not null, primary key 
# name  :string(255) 
# email  :string(255) 
# created_at :datetime  not null 
# updated_at :datetime  not null 
# 

class User < ActiveRecord::Base 
    attr_accessible :name, :email, :password, :password_confirmation 
    has_secure_password 

    before_save { |user| user.email = email.downcase } 
    before_save :create_remember_token 

    validates :name, presence: true, length: { maximum: 50 } 
    VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i 
    validates :email, presence: true, 
        format:  { with: VALID_EMAIL_REGEX }, 
        uniqueness: { case_sensitive: false } 
    validates :password, length: { minimum: 6 } 
    validates :password_confirmation, presence: true 

    private 

     def create_remember_token 
     self.remember_token = SecureRandom.urlsafe_base64 
     end 
end 

authentication_pages_spec.rb:

require 'spec_helper' 

describe "Authentication" do 

    subject {page} 
    describe "signin page" do 
    before { visit signin_path } 
    it {should have_selector('h1', text: 'Sign in')} 
    it {should have_selector('title', text: 'Sign in')} 
    end 

    describe "signin" do 
    before {visit signin_path} 

    describe "with invalid information" do 
     before {click_button "Sign in"} 

     it {should have_selector('title', text: 'Sign in')} 
     it {should have_selector('div.alert.alert-error', text: 'Invalid')} 

     describe "after visiting another page" do 
       before { click_link "Home" } 
       it { should_not have_selector('div.alert.alert-error') } 
      end 
    end 

    describe "with valid information" do 
      let(:user) { FactoryGirl.create(:user) } 
      before do 
      fill_in "Email", with: user.email 
      fill_in "Password", with: user.password 
      click_button "Sign in" 
      end 

      it { should have_selector('title', text: user.name) } 
      it { should have_link('Profile', href: user_path(user)) } 
      it { should have_link('Sign out', href: signout_path) } 
      it { should_not have_link('Sign in', href: signin_path) } 
      end 
    end 
end 

e l'inizio del user_spec.rb:

# == Schema Information 
# 
# Table name: users 
# 
# id   :integer   not null, primary key 
# name  :string(255) 
# email  :string(255) 
# created_at :datetime  not null 
# updated_at :datetime  not null 
# 

require 'spec_helper' 

describe User do 

    before do 
     @user = User.new(name: "Example User", email: "[email protected]", 
         password: "foobar", password_confirmation: "foobar") 
    end 

    subject { @user } 

    it { should respond_to(:name) } 
    it { should respond_to(:email) } 
    it { should be_valid } 
    it { should respond_to(:password_digest) } 
    it { should respond_to(:password) } 
    it { should respond_to(:password_confirmation) } 
    it { should respond_to(:authenticate) } 
    it { should respond_to(:remember_token) } 

    describe "remember token" do 
     before { @user.save } 
     its(:remember_token) { should_not be_blank } 
    end 
. 
. 
. 

Qualsiasi aiuto sarebbe molto apprezzato!

risposta

4

Se si ottiene questo errore nella produzione di Heroku, dopo si esegue:

heroku run rake db:migrate 

è necessario riavviare l'app:

heroku restart 
+0

Questo risolve il mio problema come era solo su Heroku. Ho provato a testare la registrazione prima di migrare. Dopodiché, anche "heroku run db: migrate' non risolverebbe il problema. Come al solito, avrei dovuto provare a spegnerlo e riaccenderlo. – brodney

2

Hai generato la migrazione per l'aggiunta della colonna al modello Utente?

$ rails generate migration add_remember_token_to_users 

Dopo questa modifica il file di migrazione per aggiungere il nuovo campo remember_token

e

Dopo di che è necessario fare

$ bundle exec rake db:migrate 
$ bundle exec rake db:test:prepare 

le annotazioni del modello non mostrare la colonna. Assicurati di aver eseguito i comandi sopra.

+1

Grazie per la risposta! Avevo generato la migrazione, ma non avevo aggiunto il nuovo campo. Tuttavia, quando ho aggiunto la colonna e l'indice e ho eseguito i comandi db, ho ricevuto gli stessi errori. Così, ho rimosso il file _add_remember_token_to_users con un semplice 'rm' nella directory, quindi ho eseguito nuovamente i comandi. Il mio file ora sembra {AddRememberTokenToUsers classe skirmishdirmish

+0

controlla nella tabella se la colonna esiste – rangalo

+0

Lo fa. Pensi che sarebbe meglio solo ripristinare tutte queste modifiche e ricominciare da capo? In tal caso, potresti indicarmi il modo più sicuro per farlo senza danneggiare altri file? – skirmishdirmish

-1

Ho appena avuto lo stesso problema, ottenendo il metodo non definito find_by_remember_token.

Ecco che cosa ho fatto per risolvere il problema:

heroku run rake db:migrate 

e spingerla all'interno per Heroku nuovo

git push heroku 
2

ho avuto prova simile errore di sicuro. quello che ho fatto è generare la colonna remember_token con un tipo di stringa.

rails generate migration add_remember_token_to_users remember_token:string --force 

rake db:migrate RAILS_ENV=test 

dopo, passaggio di prova.

+0

Questo ha funzionato per me quando ho riscontrato il problema. La domanda è "perché", ma suppongo che scoprirò quando mi immergerò più profondamente. – MarsAtomic

0

Ho incontrato lo stesso problema durante l'apprendimento del tutorial di Mhartl. L'ho risolto. questo problema si presenta coz quando il database ha già alcuni dati utente, quindi la migrazione "remember_token" non funzionerà. è necessario pulire prima la data, quindi eseguire db: migrate.in questo modo:

rake db: goccia db: creare rake db: migrate (fate attenzione: questo cancellerà tutti i dati)

speranza aiuto

Problemi correlati