首页 > 解决方案 > 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)

标签: ruby-on-railsrubyrspecrspec-rails

解决方案


默认情况下validates_presence_of,将错误消息视为can't be blank. 但是,当您设置自定义验证消息时,您必须with_message在规范中使用相同的验证消息

it { should validate_presence_of(:properties).with_message('This field is non editable') }

带有 with_message 的 validate_presence_of 示例


推荐阅读