Search code examples
ruby-on-railsrubyrspecrspec-rails

Ruby on Rails: RSpec not working with validation


I have fairly simple model but I'm getting RSpec failures that I cannot find the solution to.

Model -

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

This is the failure that I am getting:

Failure -

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)

Solution

  • By default validates_presence_of consider error message as can't be blank. but, as you are setting custom validation message then, you have to verify the same using with_message in spec

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

    Example for validate_presence_of with with_message