今天在写一个验证的时候,不知道为何,使用 rspec 测是总是失败
提示消息是
Failures:
1) DefaultWarningConfig has a valid factory
Failure/Error: expect(build(:default_warning_config)).to be_valid
NoMethodError:
undefined method count' for #<DefaultWarningConfig:0x007f9acdcaaf20>
# ./app/models/default_warning_config.rb:7:in
only_one_record'
# ./spec/models/default_warning_config_spec.rb:5:in `block (2 levels) in '
Finished in 0.99455 seconds (files took 2.29 seconds to load) 4 examples, 1 failure
可以看到,此处确实是 DefaultWarningConfig 这个对象
源码倒是蛮简单的
class DefaultWarningConfig < ActiveRecord::Base
validates :pre_warning,:absolute_temp_min,:absolute_temp_max, :presence => true,:numericality => true
validate :only_one_record
def only_one_record
p self.class
errors.add(:id,"只允许有一条记录") if self::count !=0
end
end
将此处的 self::count 换成 DefaultWarningConfig::count 即可
但是我觉得没道理啊 self.class 不就是 DefaultWarningConfig 么