【发布时间】:2017-12-21 00:39:34
【问题描述】:
在我的用户模型中,我有一个名为 normalize_params 的 before_validation 方法,它使用小写。
class User < ApplicationRecord
before_validation :normalize_params, on: [:create, :update]
validates :email, :presence => true
validates :email, :uniqueness => true
validates :username, :presence => true
validates :username, :uniqueness => true
validates_confirmation_of :password
scope :all_users_except, -> (current_user) {
where.not(id: current_user)
}
has_attached_file :avatar, styles: { medium: "300x300>", thumb:
"100x100>" }, default_url: "/images/missing.png"
validates_attachment_content_type :avatar, content_type:
/\Aimage\/.*\z/
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
private
def normalize_params
self.name = name.downcase.titleize
self.email = email.downcase
self.home = home.downcase.titleize
end
end
所有这些都在我的应用程序中完美运行,但是当我遇到此错误时,我的测试会中断...
NoMethodError:
undefined method `downcase' for nil:NilClass
这是我的测试...
require 'rails_helper'
describe User, 'validation' do
it { should validate_presence_of :email }
it { should validate_presence_of :username }
it { should validate_presence_of :password }
end
如果我去掉 before_validation 和 normalize_params,那么我的测试就通过了。
【问题讨论】:
标签: ruby-on-rails validation rspec