首页 > 解决方案 > Rspec 应该 AttributeDoesNotExistError

问题描述

我有一个附加到用户的客户端模型,所有规范测试都通过了。后来我意识到客户不需要登录,所以我删除了关联。我添加了f_namel_name列。validates_presence_of当我为该列运行应该匹配器时f_name,我收到错误...

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

我在应用程序中使用该属性,它确实存在。我可以使用种子文件填充数据库,并在应用程序中使用它。

我已经删除了数据库并重新创建了它,并db:test:prepare认为测试数据库的架构可能没有改变。

为什么我会遇到这个问题?

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

架构.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 

客户端.rb

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

标签: ruby-on-rails-5rspec-railsshoulda

解决方案


你能试试这样的吗。

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

推荐阅读