Rspec shoulda AttributeDoesNotExistError

1k views Asked by At

I have a clients model that was attached to users and all spec tests were passing fine. Later I realized that the clients would not need to log in so I removed the association. I added f_name and l_name columns. When I run shoulda matcher validates_presence_of for the f_name column, I get the error...

Shoulda::Matchers::ActiveModel::AllowValueMatcher::AttributeDoesNotExistError: The matcher attempted to set :f_name on the Client to nil, but that attribute does not exist.

I am using the attribute in the app and it does exist. I am able to populate the database with a seed file along with using it in the app.

I have dropped the database and recreated it along with db:test:prepare thinking that maybe the test database's schema did not change.

Why would I be having this problem?

rails_helper.rb

require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
require 'shoulda/matchers'


Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :rails
  end
end

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

schema.rb

create_table "clients", force: :cascade do |t|
  t.string "f_name"
  t.string "m_name"
  t.string "l_name"
  ...
end

client_spec.rb

require "rails_helper"

RSpec.describe Client, type: :model do
  it {should validate_presence_of(:f_name)}
  it {should validate_presence_of(:l_name)}
  ...
end 

client.rb

class Client < ApplicationRecord
  validates_presence_of :f_name, :l_name
  ...
end
1

There are 1 answers

1
Kedarnag Mukanahallipatna On

Can you try something like this.

RSpec.describe Client, type: :model do
  subject { Client.new(f_name: 'first_name', l_name: 'last_name') }

  it { should validate_presence_of(:f_name) }
end