Chapter 8 Rails Tutorial Remember Token Errors
Asked Answered
K

6

6

This chapter is on adding remember tokens to ensure that the user signin status is remembered and that the session is only cleared when the user explicitly signs out. I understand the importance of having this feature in my app, so want to make sure that it works correctly. I'm getting a bunch of errors though, when I run

$ bundle exec rspec spec/

and I suspect they have to do with my user model, as they all but one contain:

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

and the last contains

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

and then point to my user_spec.rb, user.rb, and and authentication_pages_spec.rb files, which I have included most of (the pertinent parts) here.

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+\-.]+@[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

and the beginning of 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
.
.
.

Any help would be much appreciated!

Klagenfurt answered 29/4, 2012 at 17:45 Comment(0)
Z
4

If you get this error in production on Heroku, after you run:

heroku run rake db:migrate

you need to restart your app:

heroku restart
Zehe answered 14/7, 2014 at 3:33 Comment(1)
This fixed my issue as it was only on Heroku. I tried to test sign up before migrating. After that, even heroku run db:migrate would not fix the issue. As usual, I should have tried turning it off and on again.Madigan
I
2

Did you generate the migration for adding the column to the User model ?

$ rails generate migration add_remember_token_to_users

After this edit the migration file to add the new field remember_token

and

After that you need to do

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

Your annotations on the model don't show the column. Make sure you executed the above commands.

Included answered 29/4, 2012 at 18:21 Comment(5)
Thanks for your response! I had generated the migration, but hadn't added the new field. However, when I added the column and index and ran the db commands, I got the same errors. So, I removed the _add_remember_token_to_users file by a simple 'rm' in the directory, then ran the commands again. My file now looks like {class AddRememberTokenToUsers < ActiveRecord::Migration def change add_column :users, :remember_token, :string add_index :users, :remember_token end end } but now when I run $ bundle exec rspec spec/models/user_spec.rb, it says it cannot load the file...Klagenfurt
check in the table if the column existsIncluded
It does. Do you think it would be best just to roll back all of these changes and start fresh? If so, could you point me to the safest way to do that without damaging other files?Klagenfurt
Hi, also check the table in test database schema. Make sure you executed the bundle exec rake db:test:prepare command. Other than that i can think of nothing which can give you this error.Included
I had the exact same error and id what @Klagenfurt did in the comment above except i reran the bundle exec rake commands afterwards. The tests then passed.Mockingbird
P
2

I got similar test fail error. what I did is to generate the remember_token column with a string type.

rails generate migration add_remember_token_to_users remember_token:string --force

rake db:migrate RAILS_ENV=test

after that, test pass.

Peddler answered 18/6, 2013 at 23:24 Comment(1)
This worked for me when I encountered the problem. The question is "why," but I suppose I'll find out when I diver deeper.Adumbrate
A
0

I met the same issue while learning Mhartl tutorial.I solved it. this problem shows up coz when you database already have some user data, then "remember_token" migrate won't work. you must clean your date firt,then do db:migrate.like this:

rake db:drop db:create rake db:migrate (be carefull:this will erase all your data)

hope help

Adipose answered 7/5, 2014 at 16:41 Comment(0)
I
0

Not sure why it wasnt mentioned (or i missed it). the "login with remembering" test has the line "assert_equal cookies['remember_token'], assigns(:user).remember_token". All you need to do to get the test to pass is replace that line with "assert_not cookies[:remember_token].blank?"

Imperception answered 8/3, 2022 at 9:45 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Cozmo
L
-1

I just had the same problem, getting undefined method find_by_remember_token.

Here's what I did to fix it:

heroku run rake db:migrate

Then push to heroku again

git push heroku
Letterpress answered 9/8, 2012 at 14:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.