rails 3.2.1使用has_secure_password显示消息“表xxx没有列名为password”

时间:2013-03-22 20:35:29

标签: ruby-on-rails-3 unit-testing activerecord

我是使用rails的新手,我一直在尝试针对模型使用has_secure_password的控制器构建一些测试。按照测试:

require 'test_helper'

class UsersControolerTest < ActionController::TestCase
  setup do
    @dados_user = {
      full_name: "Fulano",
      bio: "lorem ipsun lorum lorem ipsun lorum lorem ipsun lorum",
      location: "Brazil",
      email: "fulano@gmail.com",
      password: "123456",
      password_confirmation: "123456"
    }    
  end

  test "Cria usuário banco" do
    assert_difference('User.count') do
      post :create, user: @dados_user
    end
  end
end

当我运行测试时,收到以下错误消息:

ActiveRecord :: StatementInvalid:SQLite3 :: SQLException:表用户没有列  命名密码:INSERT INTO“users”(“full_name”,“email”,“password”,“locatio n“,”bio“,”created_at“,”updated_at“,”id“)......

模型的代码是:

class User < ActiveRecord::Base
  has_many :rooms, :dependent => :destroy
  has_many :reviews, :dependent => :destroy

  scope :confirmed, where('confirmed_at IS NOT NULL')

  has_secure_password  
  attr_accessible :bio, :email, :full_name, :location, :password,
    :password_confirmation

  validates_presence_of :email, :full_name, :location
  validates_length_of :bio, :minimum => 30, :allow_blank => false
  validates_format_of :email, :with => /\A[^@]+@([^@\.]+\.)+[^@\.]+\z/
  validates_uniqueness_of :email

  before_create :generate_token

  def generate_token
    self.confirmation_token = SecureRandom.urlsafe_base64
  end

  def confirm!
    return if confirmed?

    self.confirmed_at = Time.current
    self.confirmation_token = ''
    save!
  end

  def confirmed?
    confirmed_at.present?
  end

  def self.authenticate(email, password)
    confirmed.find_by_email(email).try(:authenticate, password)
  end
end

有人可以帮助我吗? 提前谢谢。

P.S:遵循迁移代码

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :full_name
      t.string :email
      t.string :password
      t.string :location
      t.text :bio

      t.timestamps
    end

    add_index :users, :email, :unique => true
  end
end

以下迁移是关于使用has_secure_password

class RenamePasswordOnUsers < ActiveRecord::Migration
  def up
    rename_column :users, :password, :password_digest
  end

  def down
  end
end

class AddConfirmationFieldsToUsers < ActiveRecord::Migration
  def change
    add_column :users, :confirmed_at, :datetime
    add_column :users, :confirmation_token, :string
  end
end

1 个答案:

答案 0 :(得分:0)

这一切都很好。但是你还必须运行rake:db:test:prepare。运行rake:db:migrate设置您的开发数据库,​​但它不会设置您的测试数据库。

所以,运行:

rake:db:test:prepare

你应该会发现你不再犯这个错误。