ruby-on-rails - Ruby on Rails:RSpec 无法使用验证
问题描述
我有一个相当简单的模型,但是我遇到了我找不到解决方案的 RSpec 故障。
模型 -
store_accessor :properties, :fields
store_accessor :priorities
belongs_to :user
belongs_to :external_service
validates :user, :external_service, presence: true
validate :service_enabled?
validates_presence_of :properties, message => "This field is non editable"
Rspec -
require 'rails_helper'
module Application
describe Integration, type: :model do
it { should validate_presence_of(:user) }
it { should validate_presence_of(:external_service) }
it { should validate_presence_of(:properties) }
context 'external service' do
let(:service) { Application::ExternalService.new }
before do
allow(subject).to receive(:external_service).and_return(service)
end
end
end
end
这是我得到的失败:
失败 -
Application::Integration should require properties to be set
Failure/Error: it { should validate_presence_of(:properties) }
Expected errors to include "can't be blank" when properties is set to nil,
got errors:
* "can't be blank" (attribute: user, value: nil)
* "can't be blank" (attribute: external_service, value: nil)
* "The service must be enabled to add an integration." (attribute: external_service, value: nil)
* "This field is non editable" (attribute: properties, value: nil)
解决方案
默认情况下validates_presence_of
,将错误消息视为can't be blank
. 但是,当您设置自定义验证消息时,您必须with_message
在规范中使用相同的验证消息
it { should validate_presence_of(:properties).with_message('This field is non editable') }
推荐阅读
- c# - 使用 TreeNode 作为用户设置
- php - PHP arrayToCollection
- graylog - Graylog 开/关状态折线图
- r - 保留跨越多个时间范围的行
- laravel - formatLocalized,格式化分钟
- prometheus - Prometheus:将现有数据迁移到远程存储 CrateDB
- svn - 有什么方法可以帮助避免意外提交 TortoiseSVN 中的 svn:externals?
- powershell - 如果文件不存在则返回失败
- mysql - 检索最接近输入日期的日期
- swift - 试图理解 .layoutMarginsGuide 内的自定义部分 Header for a tableView 感到困惑