0

我是一个使用 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", "location", "bio", "created_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

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

PS:按照迁移码

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
4

1 回答 1

0

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

所以,运行:

rake:db:test:prepare

你应该会发现你不再得到那个错误。

于 2013-03-24T07:45:36.280 回答