Rails仅在测试时生成错误的SQL

时间:2013-04-23 02:51:25

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

我有这堂课:

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

  attr_accessor :password
  before_save :encrypt_password

  validates_confirmation_of :password
  validates_presence_of :password, :on => :create
  validates_presence_of :email
  validates_uniqueness_of :email

  def encrypt_password
    if password.present?
        self.password_salt = BCrypt::Engine.generate_salt
        self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
    end
  end

  def self.authenticate(email, password)
    user = find_by_email(email)
    if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
      user
    else
      nil
    end
  end
end

它映射到此表:

  create_table "users", :force => true do |t|
    t.string   "email"
    t.string   "password_hash"
    t.string   "password_salt"
    t.datetime "created_at",    :null => false
    t.datetime "updated_at",    :null => false
  end

我写过这个测试:

require 'test_helper'

class UserTest < ActiveSupport::TestCase
  test "primary case" do
    my_user = User.new(users(:matching_password))
    assert my_user.save, "Didn't save valid user"
  end
end

我的输出是:

  1) Error:
test_primary_case(UserTest):
ActiveRecord::StatementInvalid: SQLite3::SQLException: table users has no column
 named password: INSERT INTO "users" ("email", "password", "password_confirmatio
n", "created_at", "updated_at", "id") VALUES ('MyString', 'MyString', 'MyString'
, '2013-04-23 02:39:43', '2013-04-23 02:39:43', 781772301)
    c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/sqlite3-1.3.7-x86-mingw
32/lib/sqlite3/database.rb:91:in `initialize'
    c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/sqlite3-1.3.7-x86-mingw
32/lib/sqlite3/database.rb:91:in `new'
    c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/sqlite3-1.3.7-x86-mingw
32/lib/sqlite3/database.rb:91:in `prepare'
    c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/sqlite3-1.3.7-x86-mingw
32/lib/sqlite3/database.rb:134:in `execute'
. . .

我在使用此代码时没有问题,为什么现在错误的SQL呢?

1 个答案:

答案 0 :(得分:3)

users.yml文件中有什么内容? users(:matching_password)调用可能会尝试在password属性中保存内容。