Search code examples
rubyruby-on-rails-5rspec-rails

Rspec for presence validation not working in Rails 5


Model Todo

class Todo < ApplicationRecord
  has_many :items, dependent: :destroy
  validates :title, :created_by, presence: true
end

RSpecs

require 'rails_helper'

RSpec.describe Todo, type: :model do
  it { should have_many(:items).dependent(:destroy) }
  it { should validate_presence_of(:title) }
  it { should validate_presence_of(:created_by) }
end

When i run the command bundle exec rspec, i see:

Finished in 1.82 seconds (files took 0.97238 seconds to load)
5 examples, 2 failures

Failed examples:

rspec ./spec/models/todo_spec.rb:8 # Todo should validate that :title cannot be empty/falsy
rspec ./spec/models/todo_spec.rb:9 # Todo should validate that :created_by cannot be empty/falsy

Can anyone explain why is it failing?


Solution

  • This is the issue in shoulda-matchers. You need to add to your spec_helper.rb:

    RSpec.configure do |config|
      config.include(Shoulda::Matchers::ActiveModel, type: :model)
      config.include(Shoulda::Matchers::ActiveRecord, type: :model)
    end